springboot工程如何使用阿里云OSS傳輸文件
OSS對象存儲簡介
對象存儲服務(Object Storage Service,簡稱OSS)
阿里云對象存儲OSS(Object Storage Service)是一款海量、安全、低成本、高可靠的云存儲服務,提供99.9999999999%(12個9)的數(shù)據(jù)持久性,99.995%的數(shù)據(jù)可用性。多種存儲類型供選擇,全面優(yōu)化存儲成本。非常適合存儲非結構化數(shù)據(jù),例如視頻、圖形、日志、文本文件以及各種App應用、多終端同步軟件、網(wǎng)盤下載站的文件等,單個文件的大小從1字節(jié)到48.8TB,可以存儲的個數(shù)無限制;
springboot工程使用阿里云OSS傳輸文件
在application.yml文件中引入對應的配置,一個是對應的節(jié)點,兩個是密鑰和賬號,還有一個是對應文件的名稱;


采用這樣方式進行解耦,便于后期修改。
然后需要設置一個properties類,去讀對應的配置信息用到了ConfigurationProperties類,對應掃描的是alioss;

編寫對應的工具類
@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
/**
* 文件上傳
*
* @param bytes
* @param objectName
* @return
*/
public String upload(byte[] bytes, String objectName) {
// 創(chuàng)建OSSClient實例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// 創(chuàng)建PutObject請求。
ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
//文件訪問路徑規(guī)則 https://BucketName.Endpoint/ObjectName
StringBuilder stringBuilder = new StringBuilder("https://");
stringBuilder
.append(bucketName)
.append(".")
.append(endpoint)
.append("/")
.append(objectName);
log.info("文件上傳到:{}", stringBuilder.toString());
return stringBuilder.toString();
}
}返回文件存儲的地址
在controller中編寫上傳方法;
@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {
@Autowired
private AliOssUtil aliOssUtil;
/**
* 文件上傳
* @param file
* @return
*/
@PostMapping("/upload")
@ApiOperation("文件上傳")
public Result<String> upload(MultipartFile file){
log.info("文件上傳:{}",file);
try {
//原始文件名
String originalFilename = file.getOriginalFilename();
//截取原始文件名的后綴 dfdfdf.png
String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
//構造新文件名稱
String objectName = UUID.randomUUID().toString() + extension;
//文件的請求路徑
String filePath = aliOssUtil.upload(file.getBytes(), objectName);
return Result.success(filePath);
} catch (IOException e) {
log.error("文件上傳失敗:{}", e);
}
return Result.error(MessageConstant.UPLOAD_FAILED);
}
}采用的UUID.randomUUID().toString() ,這個是隨機命名,可以防止上傳文件名稱出現(xiàn)重復。
還需要配置對應的Configuration類,初始化阿里云對象,把他交給bean進行管理
*/
@Configuration //配置類
@Slf4j
public class OssConfiguration {
//配置類 用于初始化對象
@Bean
@ConditionalOnMissingBean
public AliOssUtil aliOssUtil(AliOssProperties aliOssProperties){
log.info("開始創(chuàng)建阿里云文件上傳工具類對象:{}",aliOssProperties);
return new AliOssUtil(aliOssProperties.getEndpoint(),
aliOssProperties.getAccessKeyId(),
aliOssProperties.getAccessKeySecret(),
aliOssProperties.getBucketName());
}
}這邊是因為在Controller中使用了依賴注入,需要將對象交給bean進行管理,編寫對應的Configuration類;
到此這篇關于springboot工程使用阿里云OSS傳輸文件的文章就介紹到這了,更多相關springboot阿里云OSS傳輸文件內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
關于Springboot的擴展點DisposableBean的原理解析
這篇文章主要介紹了關于Springboot的擴展點DisposableBean的原理解析,DisposableBean是一個接口,為Spring bean提供了一種釋放資源的方式 ,只有一個擴展方法destroy(),需要的朋友可以參考下2023-05-05
各種格式的編碼解碼工具類分享(hex解碼 base64編碼)
這篇文章主要介紹了各種格式的編碼解碼工具類,集成Commons-Codec、Commons-Lang及JDK提供的編解碼方法2014-01-01

