七牛云配置

创建SpringBoot项目

application.yml

1
2
3
4
5
6
#七牛云配置
oss:
domain: http://******.hd-bkt.clouddn.com/ # 访问域名(默认使用七牛云测试域名) 测试域名有效期仅为30天,建议更换为自有域名
accessKey: ***** # 公钥 AK
secretKey: ***** # 私钥 SK
bucket: **** #存储空间名称 创建的存储空间名称

pom.xml

1
2
3
4
5
6
7
8
9
10
11
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>

<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.7.0, 7.7.99]</version>
</dependency>

UploadController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Api(tags = "上传")
@RestController
public class UploadController {

@Autowired
private UploadService uploadService;

@ApiOperation(value = "文件上传")
@PostMapping("/upload")
public ApiResult upload(@RequestPart MultipartFile file){
String url = uploadService.upload(file);
return ApiResult.success(url);
}
}

UploadServiceImpl.java

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
@Service
@Data
@ConfigurationProperties(prefix = "oss")
public class UploadServiceImpl implements UploadService {
private String accessKey;
private String secretKey;
private String bucket;
private String domain;

@Override
public String upload(MultipartFile file) {
//判断文件类型
//获取原始文件名
if (file == null){
ApiAsserts.fail("文件上传失败!");
}
String originalFileName = file.getOriginalFilename();
//对原始文件名进行判断
assert originalFileName != null;
if (!originalFileName.endsWith(".png") && !originalFileName.endsWith(".jpg") && !originalFileName.endsWith(".txt")){
//TODO 抛出错误,此处只允许.png
ApiAsserts.fail("只可以上传png格式的图片哦!");
}
String path = PathUtils.generateFilePath(originalFileName);
return uploadOss(file,path);
}

private String uploadOss(MultipartFile file , String path) {
Configuration cfg = new Configuration(Region.autoRegion());
UploadManager uploadManager = new UploadManager(cfg);
String key = path;
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);
System.out.println(putRet.key);
System.out.println(putRet.hash);
return domain+key;
} catch (QiniuException e) {
Response r = e.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException e2) {

}
}
} catch (Exception e) {

}
return "www";
}
}

PathUtils.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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();
}
}

测试

使用ApiPost进行测试

即可在浏览器中访问到此资源。