接入七牛云的环境需要
1.首先借鉴官方SDK,
七牛云官方SDK,我们看到对于JAVA的要求是在JDK8以上的版本,我们在上传和下载的时候都需要官方生成对应凭证便可以方便对我们的资源进行管理。
接入七牛云
MAVEN依赖
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.4.0, 7.4.99]</version>
</dependency>
Java SDK依赖的第三方库及其版本
<dependencies>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>happy-dns-java</artifactId>
<version>0.1.6</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
对于七牛云的所有功能都必须要授权凭证的签算需要七牛账号下的一对有效的Access Key和Secret Key
上传资源
首先创建一个七牛云配置类
@ConfigurationProperties(prefix = "application")
public class ApplicationProperties {
private String qiniu_access_key;
private String qiniu_secret_key;
private String qiniu_name;
private String qiniu_value;
}
#application 配置
application.qiniu_access_key = *******
application.qiniu_secret_key = *******
application.qiniu_name = //选项卡名称(文件夹名称)
application.qiniu_value = //七牛空间保存地址
简单上传
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
在使用Auth的过程中我们可以自定义区域,七牛云也会提示相对应的区域。
Zone zone = new Zone.Builder(Zone.zone0())
.upHttp("http://upload.qiniup.com")
.upHttps("http://upload.qiniup.com")
Configuration cfg = new Configuration(zone);
文件上传
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
try {
Response response = uploadManager.put(localFilePath, key, upToken);
//解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
} catch (QiniuException ex) {
Response r = ex.response;
try {
} catch (QiniuException ex2) {
//ignore
}
}
其中还支持字节数组上传,数据流上传,断点续上传,自定义参数上传等,详情见官网
下载资源(七牛云的私有空间和公有空间上传是一样的,下载资源的话私有空间需要生成对应访问链接的授权签名Token和对应的时间戳)
公有空间
String fileName = "公司/存储/qiniu.jpg";
String domainOfBucket = "http://devtools.qiniu.com";
String finalUrl = String.format("%s/%s", domainOfBucket, fileName);
System.out.println(finalUrl);
私有空间
String fileName = "公司/存储/qiniu.jpg";
String domainOfBucket = "http://devtools.qiniu.com";
String encodedFileName = URLEncoder.encode(fileName, "utf-8").replace("+", "%20");
String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
Auth auth = Auth.create(accessKey, secretKey);
long expireInSeconds = 3600;//1小时,可以自定义链接过期时间
String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);