前言
笔记参考
为什么?
因为如果把图片视频等文件上传到自己的应用的Web服务器,在读取图片的时候会占用比较多的资源。影响应用服务器的性能。
所以我们一般使用OSS(Object Storage Service对象存储服务)存储图片或视频。
快速开始
一、添加依赖
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.7.0, 7.7.99]</version>
</dependency>
二、配置yml文件
qiniu-oss:
# 密钥
accessKey: q9xw_WzS18ZkZrpwmq16iILG0uZkqwdmlvq8omga
secretKey: c2Y8CI201-WGHaQ2ng2yhgVfV9O_QeZZdUsdSRl_
# 空间名称
bucket: frozenpenguin
# 七牛云提供的测试域名
testUrl: http://rbx06lhom.bkt.clouddn.com/
三、编写代码
PathUtils
用于根据当前日期生成路径
public class PathUtils {
public static String generateFilePath(String fileName){
//根据日期生成路径 2022/1/15/
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
String datePath = sdf.format(new Date());
//uuid作为文件名
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//后缀和文件后缀一致
int index = fileName.lastIndexOf(".");
// test.jpg -> .jpg
String fileType = fileName.substring(index);
return new StringBuilder().append(datePath).append(uuid).append(fileType).toString();
}
}
UploadController
@RestController
public class UploadController {
@Autowired
private UploadService uploadService;
@PostMapping("/upload")
public ResponseResult uploadImg(MultipartFile img){
return uploadService.uploadImg(img);
}
}
UploadService
public interface UploadService {
ResponseResult uploadImg(MultipartFile img);
}
UploadServiceImpl
@Service
@Data
@ConfigurationProperties(prefix = "qiniu-oss")
public class OssUploadService implements UploadService {
@Override
public ResponseResult uploadImg(MultipartFile img) {
//判断文件类型
//获取原始文件名
String originalFilename = img.getOriginalFilename();
//对原始文件名进行判断(此处只允许png图片)
if(!originalFilename.endsWith(".png")){
//此处可以自定义抛出异常给前端
//throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
throw new RuntimeException("文件格式有误")
}
//如果判断通过上传文件到OSS
String filePath = PathUtils.generateFilePath(originalFilename);
String url = uploadOss(img,filePath);// 2099/2/3/wqeqeqe.png
return ResponseResult.okResult(url);
}
private String accessKey;
private String secretKey;
private String bucket;
private String testUrl;
private String uploadOss(MultipartFile imgFile, String filePath){
//构造一个带指定 Region 对象的配置类
Configuration cfg = new Configuration(Region.autoRegion());
//...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
//默认不指定key的情况下,以文件内容的hash值作为文件名
String key = filePath;
try {
InputStream inputStream = imgFile.getInputStream();
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
try {
Response response = uploadManager.put(inputStream,key,upToken,null, null);
//解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
System.out.println(putRet.key);
System.out.println(putRet.hash);
return testUrl+key;//返回文件的url
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
//ignore
}
}
} catch (Exception ex) {
//ignore
}
return "www";
}
四、测试
这里使用ApiPost测试
请求路径:xxxx/upload
请求参数:img
请求类型:File
测试上传成功,在七牛云对应空间可以查看到相应的图片