前言:七牛云是中国领先的云存储服务提供商,致力于为开发者和企业提供安全、稳定、高效的云存储解决方案。七牛云的核心产品包括对象存储、数据处理、内容分发网络(CDN)、云媒体服务等。开发者和企业可以使用七牛云的服务来存储、管理和加速他们的数据和内容,从而提升用户访问体验、降低成本、提高效率。七牛云的服务被广泛应用于网站、移动应用、视频直播、在线教育、物联网等领域。

前置条件:自行注册七牛云,创建存储空间及绑定域名,本文未做这方面讲解

官方网址:https://www.qiniu.com/

Maven

引入七牛云

1
2
3
4
5
6
<!--qiniu-->
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.2.0, 7.2.99]</version>
</dependency>

yml

配置七牛云相关

1
2
3
4
5
6
7
#文件上传
oss:
qiniu:
url: # 访问域名
accessKey: #公共密钥
secretKey: #私钥
bucketName: #空间名

config文件

创建七牛云config文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
* @Auther: chang
* @Date: 2023/6/17 - 06 - 17 - 22:31
* @Description: com.listen.config
* @version: 1.0
*/
@Data
@Configuration
public class QiNiuYunConfig {

/**
* 七牛域名
*/
@Value("${oss.qiniu.url}")
private String url;

/**
* 七牛ACCESS_KEY
*/
@Value("${oss.qiniu.accessKey}")
private String AccessKey;

/**
* 七牛SECRET_KEY
*/
@Value("${oss.qiniu.secretKey}")
private String SecretKey;

/**
* 七牛空间名
*/
@Value("${oss.qiniu.bucketName}")
private String BucketName;

}

controller

1
2
3
4
5
6
7
8
9
10
@ApiOperation(value = "七牛云文件上传", notes = "文件上传")
@PostMapping("/uploadFile")
@ResponseBody
public ResultMessage<Object> uploadFile(@RequestPart("file") MultipartFile file) {
if (!file.isEmpty()) {
String url = uploadService.uploadFile(file);
return ResultUtil.data(url);
}
return ResultUtil.error(ResultCode.FILE_UPLOAD_ERROR);
}

service

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import com.google.gson.Gson;
import com.listen.common.ResultCode;
import com.listen.common.Constants;
import com.listen.config.QiNiuYunConfig;
import com.listen.config.exception.ServiceException;
import com.listen.service.FileService;
import com.listen.utils.StringUtils;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;

/**
* @Auther: chang
* @Date: 2023/6/17 - 06 - 17 - 22:36
* @Description: com.listen.service.impl
* @version: 1.0
*/
@Service
public class FileServiceImpl implements FileService {

private static final Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);


private final QiNiuYunConfig qiNiuYunConfig;
private final UploadManager uploadManager;
private final Auth auth;
private final String url;

private String getToken() {
return auth.uploadToken(qiNiuYunConfig.getBucketName());
}

public FileServiceImpl(QiNiuYunConfig qiNiuYunConfig, @Value("${oss.qiniu.url}") String url) {
this.qiNiuYunConfig = qiNiuYunConfig;
this.url = url;
this.uploadManager = new UploadManager(new Configuration(Zone.zone2()));
this.auth = Auth.create(qiNiuYunConfig.getAccessKey(), qiNiuYunConfig.getSecretKey());
}

/**
* 上传文件
*
* @param file
* @return
*/
@Override
public String uploadFile(MultipartFile file) {
try {
String fileName = file.getOriginalFilename();
String imgName = Constants.FILE_KEY_PREFIX_LISTEN + StringUtils.getRandomImgName(fileName);
FileInputStream inputStream = (FileInputStream) file.getInputStream();
Response res = uploadManager.put(inputStream, imgName, getToken(), null, null);
if (!res.isOK()) {
logger.error("上传七牛出错: {}", res);
throw new ServiceException(ResultCode.FILE_UPLOAD_QINIU_ERROR);
}
DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
return url + "/" + putRet.key;
} catch (Exception e) {
logger.error("文件上传异常: {}", e.getMessage(), e);
throw new ServiceException(ResultCode.FILE_UPLOAD_ERROR);
}
}
}