Java上傳文件到阿里雲對象存儲器OSS
獲取accessKeyId的方法。在阿里雲的登錄頁面點擊自己的頭像。
參考代碼如下:
public String uploadFileAvatar(MultipartFile file) {
//不同的服務器,地址不同
String endpoint = "your endpoint";
String accessKeyId = "your accessKeyId";
String accessKeySecret = "your accessKeySecret";
String bucketName = "guli-file";
try {
// 創建OSS實例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//獲取上傳文件輸入流
InputStream inputStream = file.getInputStream();
//獲取文件名稱
String fileName = file.getOriginalFilename();
//1 把文件按照日期進行分類
//獲取當前日期
// 2019/11/12
String datePath = new DateTime().toString("yyyy/MM/dd");
//拼接
// 2019/11/12/123.jpg
fileName = datePath+"/"+fileName;
//調用oss方法實現上傳
//第一個參數 Bucket名稱
//第二個參數 上傳到oss文件路徑和文件名稱 aa/bb/1.jpg
//第三個參數 上傳文件輸入流
ossClient.putObject(bucketName,fileName , inputStream);
// 關閉OSSClient。
ossClient.shutdown();
//把上傳之后文件路徑返回
//需要把上傳到阿里雲oss路徑手動拼接出來
// https://test123.oss-cn-beijing.aliyuncs.com/01.jpg
String url = "https://"+bucketName+"."+endpoint+"/"+fileName;
return url;
}catch(Exception e) {
e.printStackTrace();
return null;
}
}
官網SDK使用文檔地址:https://help.aliyun.com/document_detail/84781.html?spm=a2c4g.11186623.6.957.261c46a1nTuslQ