使用七牛云对象存储进行文件上传
一、为什么不将文件存到应用服务器?
因为存在应用服务器中,文件会比普通JSON数据大,每一次读取都要从应用服务器中读取文件,会消耗更多的时间和带宽,那么应用服务器响应时长会增长。在实际开发过程中,我们都会对单独对文件进行部署。
二、七牛云基本使用
地址:https://www.qiniu.com/
需要进行认证。
认证后进入控制台 -> 对象存储 -> 空间管理
新建一个空间
记住你的空间名
进入密钥管理 复制你的 AK和SK
三、配置文件
maven依赖
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.7.0, 7.7.99]</version>
</dependency>
yml
这里就填你刚刚复制到的
四、服务端
注意:文件不能够序列化,所以不能进行日志打印!!!(博主将日志打印注释了)
@PostMapping("/applyRoleFile")
@PreAuthorize("hasAuthority('normal')")
//@SystemLog(businessName = "申请角色")
public ResponseResult applyRoleFile(@RequestBody MultipartFile file) {
return userService.applyRoleFile(file);
}
@Data
@Service
@ConfigurationProperties(prefix = "oss")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
//上传凭证
private String accessKey;
private String secretKey;
private String bucket;
@Override
public ResponseResult applyRoleFile(MultipartFile file) {
//判断文件类型
//获取原始文件名
String originalFilename = file.getOriginalFilename();
//对原始文件名进行判断.
// 只要pdf文件
if (!originalFilename.endsWith(".pdf")) {
throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
}
//生成默认文件名
String filePath = PathUtils.generateFilePath(originalFilename);
//判断通过上传文件到OSS
String url = uploadOSS(file, filePath);
/**
这里是将地址url更新到数据库 这里就不展示了 主要是前面的那一块
*/
return ResponseResult.okResult();
}
private String uploadOSS(MultipartFile file, String filePath) {
//构造一个带指定 Region 对象的配置类
// 即你的空间是哪个地区,这里使用自动帮你填写
Configuration cfg = new Configuration(Region.autoRegion());
UploadManager uploadManager = new UploadManager(cfg);
//默认不指定key的情况下,以文件内容的hash值作为文件名
String key = filePath;
try {
InputStream inputStream = file.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);
//这个是上传到七牛云服务器的路径定义
return "http://r9yeel75m.hn-bkt.clouddn.com/" + key;
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
//ignore
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "error";
}
五、测试
使用postman测试