本博客代码下载地下:https://github.com/hcitlife/QiNiuDemo
准备工作注册之后登录,然后按如下步骤操作:
接下来到开发者中心--SDK下载--Java SDK,参考里面的文档编写代码就可以了。
服务器端代码示例
第一步:创建SpringBoot项目,添加依赖:
org.springframework.boot
spring-boot-starter-web
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
com.qiniu
qiniu-java-sdk
7.4.0
com.qiniu
happy-dns-java
0.1.6
com.squareup.okhttp3
okhttp
3.14.8
compile
com.google.code.gson
gson
2.8.6
compile
第二步:在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 deletes(String... keys) {
Map 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 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进行测试:
结果: