首先去七牛云官网领取一个免费的存储空间(后面用到的密钥,点击右侧登陆的头像,下面有密钥管理)
一:新建一个spirngboot项目,导入依赖编写配置类,把需要改的配置全部抽取出来(我这里最后一个配置,是因为我在存储空间中建了一个文件夹,我把上传的图片都放到这个文件夹中)com.qiniu qiniu-java-sdk[7.7.0, 7.7.99] com.google.code.gson gson2.8.5
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; // 空间里的文件夹
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;
}
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 upload(@RequestParam("file") MultipartFile file){
//上传文件,上传到哪呢?图片服务器七牛云
//把图片发放到距离图片最近的服务器上,降低我们自身服务器的带宽消耗
String imagePath = qiniuUtils.upload(file);
if (!imagePath.isEmpty()){
//上传成功
return R.success(imagePath);
}
return R.error("图片上传失败!");
}
}
简单的测试页面 index.html
demo
返回结果集R:
import java.util.HashMap; import java.util.Map; public class R{ private Integer code; //编码:1成功,0和其它数字为失败 private String msg; //错误信息 private T data; //数据 private Map map = new HashMap(); //动态数据 public static R success(T object) { R r = new R (); r.data = object; r.code = 1; return r; } public static R error(String msg) { R r = new R(); r.msg = msg; r.code = 0; return r; } public R 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; } }



