本文主要是介绍SpringBoot整合七牛云qiniu,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、参考项
七牛云 COS(官网): 对象存储 Kodo_云存储_海量安全高可靠云存储_oss - 七牛云
qiniu SDK for Java(官网): Java SDK_SDK 下载_对象存储 - 七牛开发者中心
二、引入Pom文件
<!-- https://mvnrepository.com/artifact/com.qiniu/qiniu-java-sdk -->
<dependency><groupId>com.qiniu</groupId><artifactId>qiniu-java-sdk</artifactId><version>7.1.0</version>
</dependency>
三、定义抽象类
public abstract class BaseObjectStorage {/*** 上传文件** @param pathAndName* @param file*/public abstract void upload(String pathAndName, File file);/*** 授权** @param pathAndName* @param time* @return*/public abstract String authorize(String pathAndName, long time);/*** 授权(路径全)** @param pathAndName* @param time* @return*/public abstract String authorizeAllName(String pathAndName, long time);/*** 临时上传文件授权** @param dir* @return*/public abstract Map<String, Object> tokens(String dir);/*** 删除文件** @param pathAndName*/public abstract void deleteFile(String pathAndName);public String getFilePathPrefix();}
四、COS实现类
package cn.xhh.view.core.objectstorage;import java.io.File;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Maps;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;public class QiNiuObjectStorage implements BaseObjectStorage {private static final Logger logger = LoggerFactory.getLogger(QiNiuObjectStorage.class);private Auth auth;private static UploadManager uploadManager = new UploadManager();private String accessKeyId;private String accessKeySecret;private String bucketName;public QiNiuObjectStorage(ObjectStorageInfo objectStorageInfo) {this.accessKeyId = objectStorageInfo.getAccessKeyId();this.accessKeySecret = objectStorageInfo.getAccessKeySecret();this.bucketName = objectStorageInfo.getBucketName();auth = Auth.create(accessKeyId, accessKeySecret);}@Overridepublic void upload(String pathAndName, File file) {try {Response response = uploadManager.put(file.getAbsolutePath(), pathAndName,auth.uploadToken(bucketName, pathAndName));if (response.isOK()) {logger.info("{} 七牛上传成功", pathAndName);} else {logger.info("{} 七牛上传失败,详情{}", pathAndName, response.bodyString());}} catch (QiniuException e) {logger.error("七牛上传失败", e);}}@Overridepublic String authorize(String pathAndName, long time) {return "";}@Overridepublic String authorizeAllName(String pathAndName, long time) {return "";}@Overridepublic Map<String, Object> tokens(String dir) {Map<String, Object> result = Maps.newHashMap();return result;}@Overridepublic void deleteFile(String pathAndName) {}@Overridepublic String getFilePathPrefix() {return bucketName+"/";}
}
五、application配置文件
objectstorage.type: qiniu
qiniu:access-key-id: iWw70jiXXXqrGN6m44Caccess-key-secret: Dgq65WXXXX2R3clrwXcXXXWdHPQbucket-name: data
这篇关于SpringBoot整合七牛云qiniu的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!