本博客代码下载地下:https://github.com/hcitlife/QiNiuDemo
准备工作
注册之后登录,然后按如下步骤操作:
接下来到开发者中心--SDK下载--Java SDK,参考里面的文档编写代码就可以了。
服务器端代码示例
第一步:创建SpringBoot项目,添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>7.4.0</version>
</dependency>
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>happy-dns-java</artifactId>
<version>0.1.6</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.8</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
<scope>compile</scope>
</dependency>
第二步:在resources目录创建七牛属性配置文件qiniu.properties:
qiniu.access-key=AW8tBsAy-uXXdYCO6E0ZDWMYJhY5HOEBboD_MtcH
qiniu.secret-key=kezs7Q_FlHIvwxx6nnslmhoVlh8kqStSarpISjmF
qiniu.bucket=hcstore
# [{'region0':'华东'}, {'region1':'华北'},{'region2':'华南'},{'regionNa0':'北美'},{'regionAs0':''}]
qiniu.region=region2
qiniu.domain-of-bucket=http://qm6ralq5f.hn-bkt.clouddn.com/
# 链接过期时间,单位是秒,3600代表1小时,-1代表永不过期
qiniu.expire-in-seconds=-1
第三步:创建七牛配置文件QiNiuConfig.java:
@Data
public class QiNiuConfig {
private String accessKey;
private String secretKey;
private String bucket;
private Region region;
private String domainOfBucket;
private long expireInSeconds;
private QiNiuConfig(){ //单例设计模式
Properties prop = new Properties();
try {
prop.load(QiNiuConfig.class.getResourceAsStream("/qiniu.properties"));
accessKey = prop.getProperty("qiniu.access-key");
secretKey = prop.getProperty("qiniu.secret-key");
bucket = prop.getProperty("qiniu.bucket");
domainOfBucket = prop.getProperty("qiniu.domain-of-bucket");
expireInSeconds = Long.parseLong(prop.getProperty("qiniu.expire-in-seconds"));
String zoneName = prop.getProperty("qiniu.region");
if(zoneName.equals("region0")){
region = Region.region0();
}else if(zoneName.equals("region1")){
region = Region.region1();
}else if(zoneName.equals("region2")){
region = Region.region2();
}else if(zoneName.equals("regionAs0")){
region = Region.regionAs0();
}else if(zoneName.equals("regionNa0")){
region = Region.regionNa0();
}else{
throw new Exception("Region对象配置错误!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static QiNiuConfig instance = new QiNiuConfig();
public static QiNiuConfig getInstance() {
return instance;
}
}
第三步:编写七牛工具类:
public class QiNiuUtil {
private static final String secretKey = QiNiuConfig.getInstance().getSecretKey();
private static final String bucket = QiNiuConfig.getInstance().getBucket();
private static final Region region = QiNiuConfig.getInstance().getRegion();
private static String accessKey = QiNiuConfig.getInstance().getAccessKey();
/**
* 上传本地文件
*
* @param localFilePath 本地文件完整路径
* @param key 文件云端存储的名称,值为null时生成随机的文件名,同名文件会发生覆盖
* @return
*/
public static String upload(String localFilePath, String key) {
UploadManager uploadManager = getUploadManager();
//...生成上传凭证,然后准备上传
Auth auth = Auth.create(accessKey, secretKey);
String upToken;
if (key != null) {
upToken = auth.uploadToken(bucket, key);//覆盖上传凭证
} else {
upToken = auth.uploadToken(bucket);
}
try {
Response response = uploadManager.put(localFilePath, key, upToken);
//解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
return putRet.key;
} catch (QiniuException ex) {
ex.printStackTrace();
return null;
}
}
/**
* 上传MultipartFile
*
* @param file
* @param key 文件云端存储的名称,值为null时生成随机的文件名,同名文件会发生覆盖
* @return
* @throws IOException
*/
public static String uploadMultipartFile(MultipartFile file,String key) {
UploadManager uploadManager = getUploadManager();
//把文件转化为字节数组
InputStream is = null;
ByteArrayOutputStream bos = null;
try {
is = file.getInputStream();
bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int len = -1;
while ((len = is.read(b)) != -1) {
bos.write(b, 0, len);
}
byte[] uploadBytes = bos.toByteArray();
Auth auth = getAuth();
String upToken;
if (key != null) {
upToken = auth.uploadToken(bucket, key);//覆盖上传凭证
} else {
upToken = auth.uploadToken(bucket);
}
//默认上传接口回复对象
DefaultPutRet putRet;
//进行上传操作,传入文件的字节数组,文件名,上传空间,得到回复对象
Response response = uploadManager.put(uploadBytes, key, upToken);
putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
return putRet.key;
} catch (QiniuException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 获取所有的bucket
*/
public static String[] getBucketsInfo() {
try {
BucketManager bucketManager = getBucketManager();
//获取所有的bucket信息
String[] buckets = bucketManager.buckets();
return buckets;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 获取文件访问地址
*
* @param fileName 文件云端存储的名称
* @return
* @throws UnsupportedEncodingException
*/
public static String fileUrl(String fileName) throws UnsupportedEncodingException {
String encodedFileName = URLEncoder.encode(fileName, "utf-8");
String publicUrl = String.format("%s/%s", bucket, encodedFileName);
Auth auth = getAuth();
long expireInSeconds = QiNiuConfig.getInstance().getExpireInSeconds();
if (-1 == expireInSeconds) {
return auth.privateDownloadUrl(publicUrl);
}
return auth.privateDownloadUrl(publicUrl, expireInSeconds);
}
/**
* 获取bucket里面所有文件的信息
*/
public static FileInfo[] getFileInfo() {
try {
BucketManager bucketManager = getBucketManager();
//文件名前缀
String prefix = "";
//每次迭代的长度限制,最大1000,推荐值 1000
int limit = 1000;
//指定目录分隔符,列出所有公共前缀(模拟列出目录效果)。缺省值为空字符串
String delimiter = "";
//列举空间文件列表
BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(bucket, prefix, limit, delimiter);
while (fileListIterator.hasNext()) {
//处理获取的file list结果
FileInfo[] items = fileListIterator.next();
return items;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 删除多个文件
*
* @param keys 文件名称数组
* @return
*/
public static Map<String, String> deletes(String... keys) {
Map<String, String> map = new HashMap<>();
try {
//设定删除的数据
BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
batchOperations.addDeleteOp(bucket, keys);
BucketManager bucketManager = getBucketManager();
//发送请求
Response response = bucketManager.batch(batchOperations);
//返回数据
BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
for (int i = 0; i < keys.length; i++) {
BatchStatus status = batchStatusList[i];
String key = keys[i];
if (status.code == 200) {
map.put(key, "delete success");
} else {
map.put(key, "delete failed");
}
}
} catch (Exception e) {
}
return map;
}
/**
* 删除bucket中的文件名称
*
* @param key 文件名称
* @return
*/
public static boolean delete(String key) {
try {
BucketManager mg = getBucketManager();
mg.delete(bucket, key);
return true;
} catch (Exception e) {
return false;
}
}
public static Auth getAuth() {
Auth auth = Auth.create(accessKey, secretKey);
return auth;
}
/**
* 获取上传管理器
*
* @return
*/
public static UploadManager getUploadManager() {
//构造一个带指定Zone对象的配置类
Configuration cfg = new Configuration(region);
//...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
return uploadManager;
}
/**
* 获取Bucket的管理对象
*
* @return
*/
public static BucketManager getBucketManager() {
Configuration cfg = new Configuration(region);
Auth auth = Auth.create(accessKey, secretKey);
BucketManager bucketManager = new BucketManager(auth, cfg);
return bucketManager;
}
}
工具类测试代码:
@SpringBootTest
class QiNiuUtilTest {
@Test
void upload1() {
String res = QiNiuUtil.upload("E:\\我的文档\\重要文档\\照片\\DSC_0645.jpg", "aaaa");
System.out.println(res);
}
@Test
void upload2() {
String res = QiNiuUtil.upload("E:\\我的文档\\重要文档\\照片\\DSC_0645.jpg", null);
System.out.println(res);
}
@Test
void fileUrl() throws UnsupportedEncodingException {
String url = QiNiuUtil.fileUrl("asdf");
System.out.println(url);
}
@Test
void uploadMultipartFile() {
}
@Test
void getAuth() {
Auth auth = QiNiuUtil.getAuth();
System.out.println(auth);
}
@Test
void getUploadManager() {
BucketManager bucketManager = QiNiuUtil.getBucketManager();
System.out.println(bucketManager);
}
@Test
void getFileInfo() {
FileInfo[] infos = QiNiuUtil.getFileInfo();
for (FileInfo item : infos) {
System.out.println(item.key);
System.out.println(item.hash);
System.out.println(item.fsize);
System.out.println(item.mimeType);
System.out.println(item.putTime);
System.out.println(item.endUser);
System.out.println();
}
}
@Test
void getBucketsInfo() {
String[] buckets = QiNiuUtil.getBucketsInfo();
for (String bucket : buckets) {
System.out.println(bucket);
}
}
@Test
void deletes() {
Map<String, String> map = QiNiuUtil.deletes("bbbb", "asdf");
map.forEach((k, v) -> System.out.println(k + "\t" + v));
}
@Test
void delete() {
boolean res = QiNiuUtil.delete("FvSQe8DCKNTZcoc-pqmmRRVfn3ba");
System.out.println(res);
}
}
第四步:创建Controller:
@RestController
@RequestMapping("/fileController")
public class FileController {
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile multipartFile) {
String res = QiNiuUtil.uploadMultipartFile(multipartFile, null);
return res;
}
}
第五步:启动项目,采用Postman进行测试:
结果: