阿里云OSS (Object Storage Service) 使用步骤:
- 创建OSS客户端
- 创建bucket
- 记住这个访问端点
获取秘钥: https://ram.console.aliyun.com/manage/ak?spm=5176.8466032.top-nav.dak.1d941450AlFahf
- 代码
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.8.0</version>
</dependency>
OSS工具类:
public class OSSUtils {
private static String endpoint="oss-cn-chengdu.aliyuncs.com";
private static String accessKeyId="你的accessKey";
private static String accessKeySecret="你的accessSecret";
private static String bucketName="bucket名字";
public static OSS getOSSClient(){
return new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
}
public static String uploadFile(String fileName,byte[] fileContent){
OSS ossClient = getOSSClient();
// 设置文件元信息
ObjectMetadata meta = new ObjectMetadata();
meta.setContentLength(fileContent.length);
meta.setContentType("image/jpeg");
// 上传文件流
ByteArrayInputStream inputStream = new ByteArrayInputStream(fileContent);
ossClient.putObject(bucketName,fileName,inputStream,meta);
ossClient.setObjectAcl(bucketName,fileName, CannedAccessControlList.PublicRead);
// 关闭oss客户端
ossClient.shutdown();
return "https://"+bucketName+"."+endpoint+"/"+fileName;
}
}
controller
@PostMapping("/upload")
public RespBean handleFileUpload(@RequestParam("files") MultipartFile[] files, HttpServletRequest request) {
if (files!=null && files.length!=0){
// String uploadsDir = "/uploads/";
// String realPathToUploads = request.getServletContext().getRealPath(uploadsDir);
// if (!new File(realPathToUploads).exists()) {
// new File(realPathToUploads).mkdir();
// }
try {
List<String> imgUrls = new ArrayList<>();
for (MultipartFile file : files) {
String orgName = file.getOriginalFilename();
String newName = UUID.randomUUID()+orgName.substring(orgName.indexOf("."));
String imgUrl = OSSUtils.uploadFile(newName, file.getBytes());
// OSSUtils.uploadFile()
// String filePath = realPathToUploads + orgName;
// File dest = new File(filePath);
// file.transferTo(dest);
// String imgUrl = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+uploadsDir+orgName;
imgUrls.add(imgUrl);
}
return RespBean.ok("上传成功",imgUrls);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return RespBean.error("上传失败");
}
}