我是靠谱客的博主 大力毛豆,最近开发中收集的这篇文章主要介绍最简单的Springboot整合七牛云方法,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

首先去七牛云官网领取一个免费的存储空间(后面用到的密钥,点击右侧登陆的头像,下面有密钥管理)

一:新建一个spirngboot项目,导入依赖


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

编写配置类,把需要改的配置全部抽取出来(我这里最后一个配置,是因为我在存储空间中建了一个文件夹,我把上传的图片都放到这个文件夹中)

qiniu:
# 公钥
accessKey: xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# 私钥
secretKey: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# 存储空间名
bucketName: menghu-image
# 域名/路径
path: http://rfzvsafj.hsfew.clouddn.com/
# 空间里存储的文件名 不需要可以删除
documentName: testImage/
# 最大文件上传,单次最大上传
spring:
servlet:
multipart:
max-request-size: 20MB
max-file-size: 2MB

编写工具类:

import com.google.gson.Gson;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.util.UUID;
@Component
public class QiniuUtils {
@Value("${qiniu.accessKey}")
private
String accessKey;
//公钥
@Value("${qiniu.secretKey}")
private
String accessSecretKey;
//私钥
@Value("${qiniu.bucketName}")
private
String bucketName;
// 存储空间
@Value("${qiniu.path}")
private
String path;
// 域名
@Value("${qiniu.documentName}")
private String documentName;
// 空间里的文件夹
/**
* @param file 前端传来的图片
* @return 图片的访问路径
*/
public String upload(MultipartFile file){
// 生成文件名
String fileName = getRandomImgName(file.getOriginalFilename());
//构造一个带指定 Region 对象的配置类
Configuration cfg = new Configuration(Region.huadong());
//根据自己的对象空间的地址选(华东)
//...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
//默认不指定key的情况下,以文件内容的hash值作为文件名
try {
byte[] uploadBytes = file.getBytes();
Auth auth = Auth.create(accessKey, accessSecretKey);
String upToken = auth.uploadToken(bucketName);
Response response = uploadManager.put(uploadBytes, documentName+fileName , upToken);
//解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
return path+documentName+fileName;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* @Description: 生成唯一图片名称
* @Param: fileName
* @return: 云服务器fileName
*/
public static String getRandomImgName(String fileName) {
int index = fileName.lastIndexOf(".");
if (fileName.isEmpty() || index == -1){
throw new IllegalArgumentException();
}
// 获取文件后缀
String suffix = fileName.substring(index).toLowerCase();
// 生成UUID
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
// 拼接新的名称
return uuid + suffix;
}
}

编写controller进行测试调用:

这里的返回结果集R使我自定义的返回结果集,需要的可以自取,在最下方,不需要也可以自己定义

import com.menghu.utils.QiniuUtils;
import com.menghu.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class PictureController {
@Autowired
private QiniuUtils qiniuUtils;
@PostMapping("/upload")
public R<String> upload(@RequestParam("file") MultipartFile file){
//上传文件,上传到哪呢?图片服务器七牛云
//把图片发放到距离图片最近的服务器上,降低我们自身服务器的带宽消耗
String imagePath = qiniuUtils.upload(file);
if (!imagePath.isEmpty()){
//上传成功
return R.success(imagePath);
}
return R.error("图片上传失败!");
}
}

简单的测试页面 index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>demo</title>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<script>
/**
* 上传图片
*/
function uploadImg(){
/**
* formData在jquey中使用需要设置:
* processData: false, // 告诉jQuery不要去处理发送的数据
* contentType: false // 告诉jQuery不要去设置Content-Type请求头
* @type {null}
*/
var fd = new FormData();
// 第一个参数为controller 接收的参数名称 , input的id
fd.append("file", document.getElementById("inputId").files[0]);
$.ajax({
url:"/upload",
type:"post",
data:fd,
processData:false,
contentType:false,
dataType:"json",
success:function(res){
console.log(res);
if (res.code == 1) {
$('#imageTest').attr('src', res.data);
} else {
alert("图片上传失败");
}
}
})
}
</script>
<div id="img">
<input type="file" name="text" id="inputId">
<input type="submit" onclick="uploadImg()">
<!-- 图片链接 -->
<img src="" id="imageTest" width="1000px">
</div>
</body>
</html>

返回结果集R:

import java.util.HashMap;
import java.util.Map;
public class R<T> {
private Integer code; //编码:1成功,0和其它数字为失败
private String msg; //错误信息
private T data; //数据
private Map map = new HashMap(); //动态数据
public static <T> R<T> success(T object) {
R<T> r = new R<T>();
r.data = object;
r.code = 1;
return r;
}
public static <T> R<T> error(String msg) {
R r = new R();
r.msg = msg;
r.code = 0;
return r;
}
public R<T> add(String key, Object value) {
this.map.put(key, value);
return this;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Map getMap() {
return map;
}
public void setMap(Map map) {
this.map = map;
}
}

最后

以上就是大力毛豆为你收集整理的最简单的Springboot整合七牛云方法的全部内容,希望文章能够帮你解决最简单的Springboot整合七牛云方法所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(82)

评论列表共有 0 条评论

立即
投稿
返回
顶部