spring boot 整合 七牛雲實作圖檔上傳
1.這裡我使用的是Maven,先添加七牛雲的依賴。
<!-- 七牛雲 -->
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.2.0, 7.2.99]</version>
</dependency>
2.根據七牛雲官方Java SDK 來編寫qiniuyun圖檔上傳的工具類。
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Client;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import groovy.util.logging.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
/**
* Created by Administrator on 2019/8/15.
*/
@Component
public class QiniuUtils {
@Value("${qiniu.accessKey}")
private String accessKey ;//上傳憑證AccessKey
@Value("${qiniu.secretKey}")
private String secretKey ;//上傳憑證secretKey
@Value("${qiniu.bucketName}")
private String bucketName ;//存儲空間名稱
@Value("${qiniu.fileDomain}")
private String fileDomain;//使用的域名
public String getAccessKey() {
return accessKey;
}
public String getSecretKey() {
return secretKey;
}
public String getBucketName() {
return bucketName;
}
public String getFileDomain() {
return fileDomain;
}
private UploadManager uploadManager;
private BucketManager bucketManager;
private Configuration c;
private Client client;
// 密鑰配置
private Auth auth;
public Client getClient(){
if (client==null) {
client=new Client(getConfiguration());
}
return client;
}
public BucketManager getBucketManager() {
if (bucketManager == null) {
bucketManager = new BucketManager(getAuth(), getConfiguration());
}
return bucketManager;
}
public UploadManager getUploadManager() {
if (uploadManager == null) {
uploadManager = new UploadManager(getConfiguration());
}
return uploadManager;
}
public Configuration getConfiguration() {
if (c == null) {
Zone z = Zone.zone0();
c = new Configuration(z);
}
return c;
}
public Auth getAuth() {
if (auth == null) {
auth = Auth.create(getAccessKey(), getSecretKey());
}
return auth;
}
//簡單上傳模式的憑證
public String getUpToken() {
return getAuth().uploadToken(getBucketName());
}
//覆寫上傳模式的憑證
public String getUpToken(String fileKey) {
return getAuth().uploadToken(getBucketName(), fileKey);
}
/**
* 将本地檔案上傳
* @param filePath 本地檔案路徑
* @param fileKey 上傳到七牛後儲存的檔案路徑名稱
* @return String
* @throws IOException
*/
public String upload(String filePath, String fileKey) throws IOException {
Response res;
try {
res = getUploadManager().put(filePath, fileKey, getUpToken(fileKey));
// 解析上傳成功的結果
DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
return fileDomain + "/" + putRet.key;
} catch (QiniuException e) {
res = e.response;
e.printStackTrace();
return "上傳失敗";
}
}
/**
* 上傳二進制資料
* @param data
* @param fileKey
* @return String
* @throws IOException
*/
public String upload(byte[] data, String fileKey) throws IOException {
Response res;
try {
res = getUploadManager().put(data, fileKey, getUpToken(fileKey));
// 解析上傳成功的結果
DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
return fileDomain + "/" + putRet.key;
} catch (QiniuException e) {
res = e.response;
e.printStackTrace();
return "上傳失敗";
}
}
/**
* 上傳輸入流
* @param inputStream
* @param fileKey
* @return String
* @throws IOException
*/
public String upload(InputStream inputStream, String fileKey) throws IOException {
Response res;
try {
res = getUploadManager().put(inputStream, fileKey, getUpToken(fileKey),null,null);
// 解析上傳成功的結果
DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
return fileDomain + "/" + putRet.key;
} catch (QiniuException e) {
res = e.response;
e.printStackTrace();
return "上傳失敗";
}
}
/**
* 删除檔案
* @param fileKey
* @return
* @throws QiniuException
*/
public boolean delete(String fileKey) throws QiniuException {
Response response = bucketManager.delete(this.getBucketName(), fileKey);
return response.statusCode == 200 ? true:false;
}
/**
* 擷取公共空間檔案
* @param fileKey
* @return String
*/
public String getFile(String fileKey) throws Exception{
String encodedFileName = URLEncoder.encode(fileKey, "utf-8").replace("+", "%20");
String url = String.format("%s/%s", fileDomain, encodedFileName);
return url;
}
/**
* 擷取私有空間檔案
* @param fileKey
* @return String
*/
public String getPrivateFile(String fileKey) throws Exception{
String encodedFileName = URLEncoder.encode(fileKey, "utf-8").replace("+", "%20");
String url = String.format("%s/%s", fileDomain, encodedFileName);
Auth auth = Auth.create(accessKey, secretKey);
long expireInSeconds = 3600;//1小時,可以自定義連結過期時間
String finalUrl = auth.privateDownloadUrl(url, expireInSeconds);
return finalUrl;
}
}
注:此執行個體我是在 配置檔案中設定好了 需要的上傳憑證AccessKey,SecretKey,bucketName,fileDomain。
#七牛雲配置
qiniu:
accessKey: xxxxxx #上傳憑證AccessKey
secretKey: xxxxxx #上傳憑證secretKey
bucketName: xxx #存儲空間名稱
fileDomain: www.xxx.* #檔案通路域名字首
在這裡我們看到通過注解@Value() 然後填入對應的路徑可以将配置檔案中設定的值,覆入屬性中
@Value("${qiniu.accessKey}")
private String accessKey ;//上傳憑證AccessKey
@Value("${qiniu.secretKey}")
private String secretKey ;//上傳憑證secretKey
@Value("${qiniu.bucketName}")
private String bucketName ;//存儲空間名稱
@Value("${qiniu.fileDomain}")
private String fileDomain;//使用的域名
好了,我們先建立一個Controller類。
3.建立controller類。
import com.chengma.devplatform.config.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;
/**
* Created by Administrator on 2019/8/15.
*/
@RestController
@RequestMapping("/api")
public class TestQiNiuResource {
@Autowired
QiniuUtils qiniuUtils;
@RequestMapping("/toIndex")
public String index(){
return "img";
}
@ResponseBody
@RequestMapping(value = "/image", method = RequestMethod.POST)
private String postUserInforUpDate(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException {
// 用來擷取其他參數
MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);
String name = params.getParameter("username");
if (!file.isEmpty()) {
FileInputStream fileInputStream = (FileInputStream) file.getInputStream();
String originalFilename = file.getOriginalFilename();
String fileExtend = originalFilename.substring(originalFilename.lastIndexOf("."));
//預設不指定key的情況下,以檔案内容的hash值作為檔案名
String fileKey = UUID.randomUUID().toString().replace("-", "") + fileExtend;
return qiniuUtils.upload(fileInputStream,fileKey);
}
return "上傳失敗";
}
}
在此我們的七牛雲圖檔上傳已經整合完成了。
ok,那讓我們來測試一下吧,我這邊是使用postman來模拟的。
4.使用postman測試圖檔上傳
将對應内容填寫進去
通過傳回的域名加對應路徑,我已經可以成功通路上傳的圖檔了。