import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.wqh.fsrm.common.ResponseResult;
import com.wqh.fsrm.common.util.MD5Utils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.web.multipart.MultipartFile;
import java.net.URL;
import java.util.*;
public class CosFile {
private static Logger log = LoggerFactory.getLogger(CosFile.class);
public static final String secretId = "";
public static final String secretKey = "";
public static final String bucket = "polz-files-1302700757";
public static final String regionString = "ap-shanghai";
public static final String url = "https://polz-files-1302700757.cos.ap-shanghai.myqcloud.com";
public static COSClient getCOSClient(){
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
Region region = new Region(regionString);
ClientConfig clientConfig = new ClientConfig(region);
clientConfig.setHttpProtocol(HttpProtocol.https);
COSClient cosClient = new COSClient(cred, clientConfig);
return cosClient;
}
/**
*
* @param file 文件
* @param contextType 文件类型
* @param path 路径
* @param
* @return
*/
public static JSONObject uploadFileToCos(MultipartFile file, String contextType, String path, String fileName) {
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(file.getSize());
metadata.setContentType(contextType);
try{
COSClient cosClient = getCOSClient();
PutObjectResult pubResult = cosClient.putObject(bucket, path + fileName, file.getInputStream(),metadata);
if(pubResult == null || StringUtils.isBlank(pubResult.getETag())){
log.error("upload to cos error, put object result is null or etag is empty, fileName {}", fileName);
return ResponseResult.failure("501","upload to cos error, put object result is null or etag is empty");
}
Map<String,Object> map = new HashMap<>();
map.put("fileMd5",pubResult.getETag());
map.put("url",url + "/" + path + fileName);
return ResponseResult.success(map);
}catch(Exception e){
log.error("upload to cos error", e);
return ResponseResult.failure("501",e.getMessage());
}
}
/**
* bucket设置为私有的时候,需要签名访问。该方法可以生成签名链接地址
* @param file 文件
* @param contextType 文件类型
* @param path 路径
* @param
* @return
*/
public static JSONObject uploadFileToCosSign(MultipartFile file, String contextType, String path, String fileName) {
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(file.getSize());
metadata.setContentType(contextType);
try{
COSClient cosClient = getCOSClient();
PutObjectResult pubResult = cosClient.putObject(bucket, path + fileName, file.getInputStream(),metadata);
if(pubResult == null || StringUtils.isBlank(pubResult.getETag())){
log.error("upload to cos error, put object result is null or etag is empty, fileName {}", fileName);
return ResponseResult.failure("501","upload to cos error, put object result is null or etag is empty");
}
String url = getSignUrl(path,fileName);
Map<String,Object> map = new HashMap<>();
map.put("fileMd5",pubResult.getETag());
map.put("url",url);
return ResponseResult.success(map);
}catch(Exception e){
log.error("upload to cos error", e);
return ResponseResult.failure("501",e.getMessage());
}
}
/**
* 根据文件路径重新生成文件名,文件名后缀为oldFilePath的后缀
*
* @param oldFilePath
* @return
*/
public static String getFileName(String oldFilePath){
String newFileName = MD5Utils.encrypt(UUID.randomUUID().toString());
if(oldFilePath.lastIndexOf(".") >=0){
newFileName = newFileName + oldFilePath.substring(oldFilePath.lastIndexOf("."));
}
return newFileName;
}
public static String getSignUrl(String path,String fileName){
// 调用 COS 接口之前必须保证本进程存在一个 COSClient 实例,如果没有则创建
// 详细代码参见本页:简单操作 -> 创建 COSClient
COSClient cosClient = getCOSClient();
// 存储桶的命名格式为 BucketName-APPID,此处填写的存储桶名称必须为此格式
String bucketName = bucket;
// 对象键(Key)是对象在存储桶中的唯一标识。详情请参见 [对象键](https://cloud.tencent.com/document/product/436/13324)
String key = path+fileName;
// 设置签名过期时间(可选), 若未进行设置则默认使用 ClientConfig 中的签名过期时间(1小时)
// 这里设置签名在半个小时后过期
Date expirationDate = new Date(System.currentTimeMillis() + 30 * 60 * 1000);
// 填写本次请求的参数,需与实际请求相同,能够防止用户篡改此签名的 HTTP 请求的参数
Map<String, String> params = new HashMap<String, String>();
params.put("param1", "value1");
// 填写本次请求的头部,需与实际请求相同,能够防止用户篡改此签名的 HTTP 请求的头部
Map<String, String> headers = new HashMap<String, String>();
headers.put("header1", "value1");
// 请求的 HTTP 方法,上传请求用 PUT,下载请求用 GET,删除请求用 DELETE
HttpMethodName method = HttpMethodName.GET;
URL url = cosClient.generatePresignedUrl(bucketName, key, expirationDate, method, headers, params);
return url.toString();
}
}
java 对接腾讯COS实现上传文件功能
最新推荐文章于 2024-06-17 11:28:32 发布