一、七牛云快速入门
快速入门
- 1、注册账号
- 2、创建存储空间, 命名
xyz
对应下面springboot
应用配置bucket
- 3、创建成功后进入该空间,获取该空间的测试域名,对应下面
springboot
应用配置中的path
- 4、点击“个人面板—密钥管理”,获取
accessKey
和 secretKey
二、application.yml中配置参数
# 七牛云配置
# bucket是创建的存储空间名
# path对应存储空间的访问域名
qiniu:
accessKey: zHy3Im3Yjxxxxxx
secretKey: LQR4mszxxxxxxxx
bucket: xyz
path: http:
三、读取application.yml中七牛云配置工具类ConstantQiniu.java
@Data
@Component
@ConfigurationProperties(prefix = "qiniu")
public class ConstantQiniu {
private String accessKey;
private String secretKey;
private String bucket;
private String path;
}
四、pom.xml
加入七牛云
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.2.0, 7.2.99]</version>
</dependency>
五、XyzController
控制类
@Controller
@RequestMapping("/admin/xyz")
public class XyzController{
@Autowired
private ConstantQiniu constantQiniu;
/** * 上传文件到七牛云存储 * @param multipartFile * @return * @throws IOException */
@PostMapping("/qiniu")
@ResponseBody
public ResultVO uploadImgQiniu(@RequestParam("file") MultipartFile multipartFile) throws IOException {
FileInputStream inputStream = (FileInputStream) multipartFile.getInputStream();
String path = uploadQNImg(inputStream, KeyUtil.genUniqueKey());
return ResultVOUtil.success(path);
}
/** * 将图片上传到七牛云 */
private String uploadQNImg(FileInputStream file, String key) {
Configuration cfg = new Configuration(Zone.zone2());
UploadManager uploadManager = new UploadManager(cfg);
try {
Auth auth = Auth.create(constantQiniu.getAccessKey(), constantQiniu.getSecretKey());
String upToken = auth.uploadToken(constantQiniu.getBucket());
try {
Response response = uploadManager.put(file, key, upToken, null, null);
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
String returnPath = constantQiniu.getPath() + "/" + putRet.key;
return returnPath;
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}
参考官网文档Java sdk -> 文件上传
部分
六、layui前端部分
upload.render({
elem: '.thumbBox',
url: '/admin/xyz/qiniu',
multiple: false,
before: function(obj){
},
done: function(res){
debugger
},
error: function(index, upload){
debugger
}
});
图片/文件上传 - layui.upload