七⽜云java(服务端)通⽤⼯具类前⾔
需要安装lombok插件。
功能列表
上传本地⽂件
上传Base64图⽚
获取⽂件访问地址
上传MultipartFile
代码
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.2.0, 7.2.99]</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.2</version>
<scope>provided</scope>
</dependency>
qiniu.properties
# 七⽜云配置
qiniu.access-key=你的accessKey
qiniu.secret-key=你的secretKey
qiniu.bucket=你的存储空间名称
# [{'zone0':'华东'}, {'zone1':'华北'},{'zone2':'华南'},{'zoneNa0':'北美'},{'zoneAs0':''}]
<=zone0
qiniu.domain-of-bucket=外链默认域名
# 链接过期时间,单位是秒,3600代表1⼩时,-1代表永不过期
QiNiuConfig.java
import com.qiniumon.Zone;
import lombok.Data;
slf4j.Slf4j;
import java.util.Properties;
/**
* 七⽜云配置
*
* @author simon
* @create 2018-08-15 10:44
**/
@Slf4j
@Data
public class QiNiuConfig {
private String accessKey;
private String secretKey;
private String bucket;
private Zone zone;
private String domainOfBucket;
private long expireInSeconds;
private static QiNiuConfig instance = new QiNiuConfig();
private QiNiuConfig(){
Properties prop = new Properties();
try {
prop.load(ResourceAsStream("/qiniu.properties"));
accessKey = Property("qiniu.access-key");
secretKey = Property("qiniu.secret-key");
bucket = Property("qiniu.bucket");
domainOfBucket = Property("qiniu.domain-of-bucket");
expireInSeconds = Long.Property("pire-in-seconds"));
String zoneName = Property("");
if(zoneName.equals("zone0")){
zone = 0();
}else if(zoneName.equals("zone1")){
zone = 1();
}else if(zoneName.equals("zone2")){
zone = 2();
}else if(zoneName.equals("zoneNa0")){
zone = Na0();
}else if(zoneName.equals("zoneAs0")){
zone = As0();
}else{
throw new Exception("Zone对象配置错误!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static QiNiuConfig getInstance(){
return instance;
}
public static void main(String[] args) {
System.out.Instance().getAccessKey());
}
}
QiNiuUtil.java
le.gson.Gson;
import com.qiniumon.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.del.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.UrlSafeBase64;
slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;字符串转数组工具类的方法
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.URLEncoder;
/**
* 七⽜上传下载⼯具类
*
* @author simon
* @create 2018-08-15 11:21
**/
@Slf4j
public class QiNiuUtil {
/**
* 上传本地⽂件
* @param localFilePath 本地⽂件完整路径
* @param key ⽂件云端存储的名称
* @param override 是否覆盖同名同位置⽂件
* @return
*/
public static boolean upload(String localFilePath, String key, boolean override){
//构造⼀个带指定Zone对象的配置类
Configuration cfg = new Instance().getZone());
//...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
//...⽣成上传凭证,然后准备上传
Auth auth = Instance().getAccessKey(), Instance().getSecretKey());        String upToken;
if(override){
upToken = auth.Instance().getBucket(), key);//覆盖上传凭证
}else{
upToken = auth.Instance().getBucket());
}
try {
Response response = uploadManager.put(localFilePath, key, upToken);
//解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
System.out.println(putRet.key);
System.out.println(putRet.hash);
return true;
} catch (QiniuException ex) {
Response r = ex.response;
try {
} catch (QiniuException ex2) {
//ignore
return false;
}
return false;
}
}
/**
* 上传Base64图⽚
* @param l 图⽚没经过base64处理的原图字节⼤⼩,获取⽂件⼤⼩的时候,切记要通过⽂件流的⽅式获取。⽽不是通过图⽚标签然后转换后获取。    * @param file64 图⽚base64字符串
* @param key ⽂件云端存储的名称
* @param override 是否覆盖同名同位置⽂件
* @return
* @throws IOException
*/
public static boolean uploadBase64(int l, String file64, String key, boolean override) throws IOException{
/*FileInputStream fis = null;
int l = (int) (new File(localFilePath).length());
byte[] src = new byte[l];
try {
fis = new FileInputStream(new File(localFilePath));
}catch (FileNotFoundException e){
e.printStackTrace();
<(e.getMessage());
<("图⽚⽂件读取失败");
return false;
}
String file64 = deToString(src, 0);*/
Auth auth = getAuth();
String upToken;
if(override){
upToken = auth.Instance().getBucket(), key);//覆盖上传凭证
}else{
upToken = auth.Instance().getBucket());
}
String url = "upload.qiniup/putb64/" + l+"/key/"+ deToString(key);
//⾮华东空间需要根据注意事项 1 修改上传域名
RequestBody rb = ate(null, file64);
Request request = new Request.Builder().
url(url).
addHeader("Content-Type", "application/octet-stream")
.addHeader("Authorization", "UpToken " + upToken)
.post(rb).build();
/
/System.out.println(request.headers());
OkHttpClient client = new OkHttpClient();
okhttp3.Response response = wCall(request).execute();
//System.out.println(response);
return response.isSuccessful();
}
/**
* 获取⽂件访问地址
* @param fileName ⽂件云端存储的名称
* @return
* @throws UnsupportedEncodingException
*/
public static String fileUrl(String fileName) throws UnsupportedEncodingException {
String encodedFileName = de(fileName, "utf-8");
String publicUrl = String.format("%s/%s", Instance().getDomainOfBucket(), encodedFileName);
Auth auth = getAuth();
long expireInSeconds = Instance().getExpireInSeconds();
if(-1 == expireInSeconds){
return auth.privateDownloadUrl(publicUrl);
}
return auth.privateDownloadUrl(publicUrl, expireInSeconds);
}
/**
* 上传MultipartFile
* @param file
* @param key
* @param override
* @return
* @throws IOException
*/
public static boolean uploadMultipartFile(MultipartFile file, String key, boolean override) {
//构造⼀个带指定Zone对象的配置类
Configuration cfg = new Instance().getZone());
/
/...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
//把⽂件转化为字节数组
InputStream is = null;
ByteArrayOutputStream bos = null;
try {
is = InputStream();
bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int len = -1;
while ((len = is.read(b)) != -1){
bos.write(b, 0, len);
}
byte[] uploadBytes= ByteArray();
Auth auth = getAuth();
String upToken;
if(override){
upToken = auth.Instance().getBucket(), key);//覆盖上传凭证
}else{
upToken = auth.Instance().getBucket());
}
//默认上传接⼝回复对象
DefaultPutRet putRet;
//进⾏上传操作,传⼊⽂件的字节数组,⽂件名,上传空间,得到回复对象
Response response = uploadManager.put(uploadBytes, key, upToken);
putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
System.out.println(putRet.key);//key ⽂件名
System.out.println(putRet.hash);//hash 七⽜返回的⽂件存储的地址,可以使⽤这个地址加七⽜给你提供的前缀访问到这个视频。
return true;
}catch (QiniuException e){
e.printStackTrace();
return false;
}catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static Auth getAuth(){
Auth auth = Instance().getAccessKey(), Instance().getSecretKey());
return auth;
}
}
推荐
oauthserver是⼀个基于Spring Boot Oauth2的完整的独⽴的Oauth2 Server微服务。仅仅需要创建相关数据表,修改数据库的连接信息,你就可以得到⼀个Oauth2 Server微服务。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。