文章目录
- 1.登录七牛云官网,注册账号并登录
- 2.在项目中导入七牛云依赖
- 3.编写创建文件名工具类
- 4.编写连接七牛云工具类
- 5.编写前端请求的Controller
- 6.上传成功
1.登录七牛云官网,注册账号并登录
2.在项目中导入七牛云依赖
<!-- 七牛云依赖 -->
<!-- https://mvnrepository.com/artifact/com.qiniu/qiniu-java-sdk -->
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>7.9.3</version>
</dependency>
3.编写创建文件名工具类
package com.handsome.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* @Author 识时务者
* @Date 2022/03/22 19:00
* @Version 1.0
*/
@SuppressWarnings({"all"})
public class CreateDestFileNameUtil {
private volatile static CreateDestFileNameUtil createDestFileUtil;
private CreateDestFileNameUtil() {
}
public static CreateDestFileNameUtil getCreateDestFileUtil() {
if (createDestFileUtil == null) {
synchronized (CreateDestFileNameUtil.class) {
if (createDestFileUtil == null) {
createDestFileUtil = new CreateDestFileNameUtil();
}
}
}
return createDestFileUtil;
}
// 上传的七牛云的获取文件名称的方法
public Map<String, Object> getDestFile(String fileName) {
String suffixName = fileName.substring(fileName.lastIndexOf("."));
// 生成文件名称通用方法
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
Random r = new Random();
StringBuilder tempName = new StringBuilder();
tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
String newFileName = tempName.toString();
Map<String, Object> map = new HashMap();
map.put("newFileName", newFileName);
return map;
}
}
4.编写连接七牛云工具类
package com.handsome.utils;
import com.alibaba.fastjson.JSON;
import com.qiniu.common.QiniuException;
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.stereotype.Component;
import java.io.InputStream;
/**
* @Author Handsome
* @Date 2022/4/24 9:39
* @Version 1.0
*/
@SuppressWarnings({"all"})
@Component
public class QiniuUtils {
// 设置需要操作的账号的AK和SK
private static final String ACCESS_KEY = "你的七牛云ACCESS_KEY";
private static final String SECRET_KEY = "你的七牛云SECRET_KEY";
// 密钥
private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
// 要上传的空间名称
private static final String BUCKETNAME = "你的七牛云创建的空间名称";
// 认证信息 不能使用static的upToken 会过期
// private static final String upToken = auth.uploadToken(BUCKETNAME);
// 外链默认域名
public static final String DOMAIN = "你的七牛云外链默认域名";
例如:http://cdn.handsomehjj.vip/handsomeforum/
public boolean upload(InputStream file, String fileName) {
//构造一个带指定 Region 对象的配置类
Configuration cfg = new Configuration(Region.huanan()); //根据自己的对象空间的地址选(华南)
//...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
//默认不指定key的情况下,以文件内容的hash值作为文件名
try {
String upToken = auth.uploadToken(BUCKETNAME);
Response response = uploadManager.put(file, "handsomeforum/" + fileName, upToken, null, null);
// 解析上传成功的结果
// DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
// 这个returnPath是获得到的外链地址,通过这个地址可以直接打开图片
// String returnPath = DOMAIN + putRet.key;
return true;
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
//ignore
}
}
return false;
}
5.编写前端请求的Controller
// axios上传头像到七牛云
@PostMapping("/user/upload/yourAvatar/{uid}")
@ResponseBody
public String uploadyourAvatar(@PathVariable String uid,
HttpServletRequest httpServletRequest,
@RequestParam(value = "file", required = true) MultipartFile file) throws Exception {
String fileName = file.getOriginalFilename();
if (fileName.isEmpty()) {
Map datamap = new HashMap<>();
datamap.put("code", 555);
datamap.put("msg", "未上传图片!");
String jasonmap = JSONObject.toJSONString(datamap);
return jasonmap;
}
// 获取destFile和newFileName
CreateDestFileNameUtil createDestFileUtil = CreateDestFileNameUtil.getCreateDestFileUtil();
Map<String, Object> map = createDestFileUtil.getDestFile(fileName);
String newFileName = (String) map.get("newFileName");
// 使用七牛云工具列上传图片
boolean upload = qiniuUtils.upload(file.getInputStream(), newFileName);
if (upload) {
// 头像图片地址
String yourAvatar = QiniuUtils.DOMAIN + newFileName;
Map datamap = new HashMap<>();
datamap.put("code", 200);
datamap.put("msg", "头像上传成功!请重新登录!");
String jasonmap = JSONObject.toJSONString(datamap);
return jasonmap;
} else {
Map datamap = new HashMap<>();
datamap.put("code", 555);
datamap.put("msg", "图片上传失败!");
String jasonmap = JSONObject.toJSONString(datamap);
return jasonmap;
}
}
6.上传成功
成功上传到七牛云后获取到图片的地址,保存到数据库,前端获取数据库中的图片地址即可访问七牛云中的图片