七牛雲 上傳圖檔到七牛雲并傳回圖檔URL
鳴謝'追逐盛夏流年':https://blog.csdn.net/j123123/article/details/
在開發項目的時候,經常會用到上傳圖檔的功能,如果把圖檔全都存放在項目路徑下,會導緻項目越來越臃腫,是以可以考慮把圖檔上傳交給第三方處理,此處我們采用七牛雲進行圖檔存儲。
一.七牛雲準備工作
1.七牛雲注冊登入
https://portal.qiniu.com/signup/choice
2.建立存儲空間
進入對象存儲菜單,點選“建立存儲空間”,這裡需要實名認證,上傳身份證正反面之類的,大概一個小時左右就認證成功了,效率真是棒棒哒~
這裡的存儲空間名稱要記住,之後在代碼裡面會用到。
二.代碼實作
1.在pom.xml添加七牛雲依賴
我的項目使用了maven管理jar包,是以隻需直接添加相應依賴即可:
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>7.1.1</version>
</dependency>
- 1
- 2
- 3
- 4
- 5
2.添加七牛雲圖檔操作工具類
package com.cn.netdisk.util;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.Base64;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
public class QiniuCloudUtil {
// 設定需要操作的賬号的AK和SK
private static final String ACCESS_KEY = "你的ACCESS_KEY";
private static final String SECRET_KEY = "你的SECRET_KEY";
// 要上傳的空間
private static final String bucketname = "你的空間名稱";
// 密鑰
private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
private static final String DOMAIN = "你的圖檔上傳路徑";
private static final String style = "自定義的圖檔樣式";
public String getUpToken() {
return auth.uploadToken(bucketname, null, , new StringMap().put("insertOnly", ));
}
// 普通上傳
public String upload(String filePath, String fileName) throws IOException {
// 建立上傳對象
UploadManager uploadManager = new UploadManager();
try {
// 調用put方法上傳
String token = auth.uploadToken(bucketname);
if(UtilValidate.isEmpty(token)) {
System.out.println("未擷取到token,請重試!");
return null;
}
Response res = uploadManager.put(filePath, fileName, token);
// 列印傳回的資訊
System.out.println(res.bodyString());
if (res.isOK()) {
Ret ret = res.jsonToObject(Ret.class);
//如果不需要對圖檔進行樣式處理,則使用以下方式即可
//return DOMAIN + ret.key;
return DOMAIN + ret.key + "?" + style;
}
} catch (QiniuException e) {
Response r = e.response;
// 請求失敗時列印的異常的資訊
System.out.println(r.toString());
try {
// 響應的文本資訊
System.out.println(r.bodyString());
} catch (QiniuException e1) {
// ignore
}
}
return null;
}
//base64方式上傳
public String put64image(byte[] base64, String key) throws Exception{
String file64 = Base64.encodeToString(base64, );
Integer l = base64.length;
String url = "http://upload.qiniu.com/putb64/" + l + "/key/"+ UrlSafeBase64.encodeToString(key);
//非華東空間需要根據注意事項 1 修改上傳域名
RequestBody rb = RequestBody.create(null, file64);
Request request = new Request.Builder().
url(url).
addHeader("Content-Type", "application/octet-stream")
.addHeader("Authorization", "UpToken " + getUpToken())
.post(rb).build();
//System.out.println(request.headers());
OkHttpClient client = new OkHttpClient();
okhttp3.Response response = client.newCall(request).execute();
System.out.println(response);
//如果不需要添加圖檔樣式,使用以下方式
//return DOMAIN + key;
return DOMAIN + key + "?" + style;
}
// 普通删除(暫未使用以下方法,未測試)
public void delete(String key) throws IOException {
// 執行個體化一個BucketManager對象
BucketManager bucketManager = new BucketManager(auth);
// 此處的33是去掉:http://ongsua0j7.bkt.clouddn.com/,剩下的key就是圖檔在七牛雲的名稱
key = key.substring();
try {
// 調用delete方法移動檔案
bucketManager.delete(bucketname, key);
} catch (QiniuException e) {
// 捕獲異常資訊
Response r = e.response;
System.out.println(r.toString());
}
}
class Ret {
public long fsize;
public String key;
public String hash;
public int width;
public int height;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
(1).擷取需要操作的賬号的AK和SK
private static final String ACCESS_KEY = "你的ACCESS_KEY";
private static final String SECRET_KEY = "你的SECRET_KEY";
- 1
- 2
進入個人中心-密鑰管理
(2).擷取要上傳的空間
private static final String bucketname = "你的空間名稱";
- 1
(3).擷取圖檔上傳URL路徑
private static final String DOMAIN = "你的圖檔上傳路徑";
- 1
(4).擷取自定義的圖檔樣式
private static final String style = "自定義的圖檔樣式";
- 1
我這裡是需要給圖檔添加水印,是以自定義了圖檔樣式,如果對于上傳圖檔沒有格式要求,則可以跳過此步驟。
将imagestyle的處理接口作為style的值即可。
3.後端代碼調用
@ResponseBody
@RequestMapping(value="/uploadImg", method=RequestMethod.POST)
public ResultInfo uploadImg(@RequestParam MultipartFile image, HttpServletRequest request) {
ResultInfo result = new ResultInfo();
if (image.isEmpty()) {
result.setCode();
result.setMsg("檔案為空,請重新上傳");
return result;
}
try {
byte[] bytes = image.getBytes();
String imageName = UUID.randomUUID().toString();
QiniuCloudUtil qiniuUtil = new QiniuCloudUtil();
try {
//使用base64方式上傳到七牛雲
String url = qiniuUtil.put64image(bytes, imageName);
result.setCode();
result.setMsg("檔案上傳成功");
result.setInfo(url);
} catch (Exception e) {
e.printStackTrace();
}
return result;
} catch (IOException e) {
result.setCode();
result.setMsg("檔案上傳發生異常!");
return result;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
4.前端代碼調用
我使用的是vue,這裡是使用了quillEditor富文本編輯器元件進行圖檔上傳,uploadImg是上傳圖檔調用的方法:
uploadImg: async function(id) {
var vm = this;
var fileInput = document.getElementById("uniqueId");
var formData = new FormData();
formData.append("image", fileInput.files[]);
this.$axios({
method: "post",
url: '/api/article/uploadImg',
data: formData
}).then((response) = >{
if (response.data.code == ) {
//後端傳回的url位址
var url = response.data.info;
if (url != null && url.length > ) {
vm.addImgRange = vm.$refs.myQuillEditor.quill.getSelection();
var index = vm.addImgRange != null ? vm.addImgRange.index: ; vm.$refs.myQuillEditor.quill.insertEmbed(index, 'image', url);
} else {
this.$Message.error("圖檔添加失敗!");
}
} else {
this.$Message.error(response.data.msg);
}
});
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24