1.去阿里云服务获取OSS存储服务
创建bucket库具体流程可以参考官方文档:
https://help.aliyun.com/zh/oss/developer-reference/sdk-code-samples/?spm=a2c4g.11186623.0.0.574971cfdGtecS
2.导入阿里云jar包
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.12.0</version>
</dependency>
3.编写工具类代码
package com.zstwd.utils;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.ByteArrayInputStream;
@Slf4j
@Component
public class AliOssUtil {
//使用自己的api密钥
private final String endpoint="";
private final String accessKeyId="";
private final String accessKeySecret="";
private final String bucketName="";
/**
* 文件上传
*
* @param bytes
* @param objectName
* @return
*/
public String upload(byte[] bytes, String objectName) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// 创建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();
}
}
//文件访问路径规则 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();
}
}
4.编写控制层代码
package com.zstwd.controller;
import com.zstwd.entity.vo.Result;
import com.zstwd.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.UUID;
@RestController
@RequestMapping("/upload")
public class UploadController {
@Autowired
private AliOssUtil aliOssUtil;
//@RequestParam("image") 是否加这个注解根据前端业务进行修改
@PostMapping
public Result upload(@RequestParam("image") MultipartFile file) {
// 获取原文件名
String originalFilename = file.getOriginalFilename();
// 获取文件后缀
String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
// 构造新的文件名
String newFilename = UUID.randomUUID().toString() + substring;
try {
String filePath =aliOssUtil.upload(file.getBytes(), newFilename);
return Result.success(filePath);
} catch (IOException e) {
e.printStackTrace();
return Result.fail(500, "上传失败");
}
}
}