目录
2.2 新建一个类ImageUpdateController
前言
本篇文章讲的是从后端上传图片至七牛云,前端发送图片到后端,后端直接可以上传至七牛云
一、前端
//将图片发给后端,在后端上传至七牛云
post("/upload/toQiniu", imgForm).then((res) => {
console.log(res);
imgUrl = res.message;//返回url
console.log(imgUrl);
});
二、后端
2.1 引七牛云依赖
在pom.xml中引入依赖
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.2.0,7.2.99]</version>
</dependency>
2.2 新建一个类ImageUpdateController
package com.example.spidercommunity.common;
import com.example.spidercommunity.common.Result;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
@RestController
@CrossOrigin
@RequestMapping("/upload")
public class ImageUploadController {
private String accessKey = "...";
private String secretKey = "...";
//上面两个key是七牛云的私钥公钥,可以在个人中心查到
private String bucket = "...";//bucket名,即空间名称
@RequestMapping("/token/get")
public Result getToken() {
// 调用七牛云的接口获取token
Auth auth = Auth.create(accessKey,secretKey);
String upToken = auth.uploadToken(bucket);
return Result.success(upToken);
}
//后端将图片上传至七牛云
@RequestMapping(value = "/toQiniu",method = RequestMethod.POST)
public Result uploadQiNiu(@RequestParam("image") MultipartFile myFileName,@RequestParam("token") String token,@RequestParam("fileKey") String fileKey) throws Exception{
InputStream stream = myFileName.getInputStream();
//构造一个带指定Zone对象的配置类
Configuration cfg = new Configuration(Zone.zone0());
//...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
Response response = uploadManager.put(stream,fileKey ,token,null, null);
// //解析上传成功的结果
// DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
//图片路径
String url = "http://xxx.com/"+fileKey;//七牛云域名
System.out.println(url);
return Result.success(url);
}
}
总结
在后端上传图片至七牛云非常方便,且通用性强,适合任何场景下的图片上传存储。个人记录,希望能帮到泥!