七牛云上传工具类-雁迟
作者:互联网
七牛云上传工具类
1、导入七牛云依赖
<!--七牛云上传-->
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>7.7.0</version>
</dependency>
<!-- 七牛云依赖Gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
2、工具类
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.IOUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.UUID;
public class SevenCowUtil {
//...七牛云生成上传凭证(可以写在配置文件中,通过@Value注入)
private static final String accessKey = "";
private static final String secretKey = "";
private static final String bucket = "";
// 七牛云访问路径的前缀(第一次网页端测试上传得到自己七牛云的路径前缀)
private static final String sevenCowPrefix = ""; //例:"http://quw05gujp.hb-bkt.clouddn.com/"
private SevenCowUtil(){
}
/**
* 上传文件服务(UUID生成文件名)
* @param multipartFile 传入文件
* @return 网络图片访问路径
*/
public static String update2Service(MultipartFile multipartFile) {
InputStream is = null;
// 文件名
String key = null;
try{
// 获取输入流
is = multipartFile.getInputStream();
String originalFilename = multipartFile.getOriginalFilename(); // 上传文件原文件名
String ext = originalFilename.substring(originalFilename.indexOf(".")); // 截取获取扩展名
key = UUID.randomUUID() + ext; //UUID生成文件名
}catch (Exception e){
e.printStackTrace();
}
return update2Service(is,key);
}
/**
* 上传文件服务(通过输入流和文件名上传)
* @param is 传入图片输入流
* @param key 上传成功后文件 name
* @return 网络图片访问路径
*/
public static String update2Service(InputStream is, String key) {
String accessPath = "上传失败!";
//构造一个带指定 Region 对象的配置类
Configuration cfg = new Configuration(Region.huabei());
//...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
try {
byte[] uploadBytes = IOUtils.toByteArray(is);
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
try {
Response response = uploadManager.put(uploadBytes, key, upToken);
//解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
// 访问路径
accessPath = sevenCowPrefix + putRet.key;
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
//ignore
}
}
} catch (UnsupportedEncodingException ex) {
//ignore
} catch (IOException e) {
e.printStackTrace();
}
return accessPath;
}
}
标签:七牛云,String,com,qiniu,key,import,上传,雁迟 来源: https://blog.csdn.net/weixin_51311218/article/details/118519608