Java后端实现七牛云上传图片、读取图片链接
添加依赖
复制代码
1
2
3
4
5
6
7
8<!--七牛云sdk--> <dependency> <groupId>com.qiniu</groupId> <artifactId>qiniu-java-sdk</artifactId> <version>7.2.11</version> </dependency>
controller
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13@Api("文件上传") @RestController public class UploadController { @Autowired private UploadService uploadService; @PostMapping(path = "/avatar",produces = "application/json") @ApiOperation("更换头像") public ResModel replaceAvator(@ApiParam("头像文件") MultipartFile file) throws IOException { return uploadService.replaceAvatar(file); } }
service接口
复制代码
1
2
3
4public interface UploadService { ResModel replaceAvatar(MultipartFile file); }
serivce实现类
复制代码
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@Service public class UploadServiceImpl implements UploadService { //上传文件 @Override public ResModel replaceAvatar(MultipartFile file) { try { /** 华北是zone1, [华东z0] [华南z2] [北美na0] [东南亚as0] */ Configuration config = new Configuration(Zone.zone0()); UploadManager manager = new UploadManager(config); String accessKey="XXX"; String secretKey="XXX"; String bucket="XXX"; Auth auth = Auth.create(accessKey, secretKey); String token = auth.uploadToken(bucket); Response response = manager.put(file.getInputStream(), file.getOriginalFilename(), token, null, null); //解析上传成功的结果 DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class); System.out.println(putRet.key);//文件名称 System.out.println(putRet.hash);//空间hash值 //根据文件名获取七牛云存储链接 String path = getFilePath(putRet.key); System.out.println(path); return path; } catch (IOException e) { throw new RuntimeException(e); } } //读取文件 public static String getFilePath(String fileName) { //自己的域名路径+文件名 String publicUrl = "XXX"+ fileName; /** * 空间为私有访问,需要验证 token String accessKey="XXX"; String secretKey="XXX"; Auth auth = Auth.create(accessKey, secretKey); long expireInSeconds = 3600; //1小时,可以自定义链接过期时间 String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds); */ return publicUrl; } }
前端
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> //action,修改后端接口路径 <form action="http://localhost:8089/avatar" method="post" enctype="multipart/form-data"> 选择需要上传的文件:<input type="file" name="file"> <input type="submit" value="提交"> </form> </body>
最后
以上就是超帅金针菇最近收集整理的关于Java实现七牛云上传图片、读取图片链接的全部内容,更多相关Java实现七牛云上传图片、读取图片链接内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复