使用
package com.ruoyi;
import java.io.File;
public class mytest {
private static String secretId = "AKID2oPDo111111111111dMp53mHfoYZGw";
private static String secretKey = "e6JTP5e222222222222GvhHYBl7C5g05";
private static String bucketName = "mht-12566666666";
private static String regionStr = "ap-beijing";
private static String domain = "https://mht-12566666666.cos.ap-beijing.myqcloud.com";
public static void main(String[] args) {
CosUtil cosUtil = new CosUtil(secretId, secretKey, bucketName, regionStr, 30L * 60L, domain);
File file = new File("C:\\Users\\13301\\Desktop\\微信截图_20220926222441.png");
Boolean put = cosUtil.put("20220926222441.png", file);
System.out.println(put ? "上传成功" : "上传失败");
//获取带签名的有有效期的图片链接,如果存储桶的权限为私有读,那么必须使用这个链接才能直接访问图片
//如果设置了公有读,那么直接拼接即可访问
String sourceUrl = cosUtil.getSourceUrl("20220926222441.png");
System.out.println(sourceUrl);
}
}
结果
上传成功
https://mht-12566666666.cos.ap-beijing.myqcloud.com/20220926222441.png?sign=q-sign-algorithm%3Dsha1%26q-ak%3DAKID2oPDoCYwmM0sb9nREwPdMp53mHfoYZGw%26q-sign-time%3D1664205380%3B1664207180%26q-key-time%3D1664205380%3B1664207180%26q-header-list%3Dhost%26q-url-param-list%3D%26q-signature%3D260170f52383e7e8ff2af5ece1edd03809ea0cc6
引入依赖
<!-- 腾讯云对象存储 SDK -->
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>5.6.105</version>
</dependency>
工具类
package com.ruoyi.project.cos.utils;
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.model.GeneratePresignedUrlRequest;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import java.io.File;
import java.io.InputStream;
import java.util.Date;
/**
* 腾讯云对象存储工具类
*
* @author DaenMax
*/
public class CosUtil {
private static String secretId;
private static String secretKey;
private static String bucketName;
private static String regionStr;
private static COSClient client;
private static Long expireTime;
private static String domain;
/**
* @param secretId
* @param secretKey
* @param bucketName 存储桶名
* @param regionStr 所属地域,例如 ap-beijing
* @param expireTime 带有sign的图片链接的有效期,单位秒数
* @param domain 访问域名,例如 https://mht-1266634666.cos.ap-beijing.myqcloud.com
*/
public CosUtil(String secretId, String secretKey, String bucketName, String regionStr, Long expireTime, String domain) {
CosUtil.secretId = secretId;
CosUtil.secretKey = secretKey;
CosUtil.bucketName = bucketName;
CosUtil.regionStr = regionStr;
CosUtil.expireTime = expireTime;
CosUtil.domain = domain;
COSCredentials cred = new BasicCOSCredentials(CosUtil.secretId, CosUtil.secretKey);
Region region = new Region(CosUtil.regionStr);
ClientConfig clientConfig = new ClientConfig(region);
client = new COSClient(cred, clientConfig);
}
/**
* 上传文件到服务器 如果key重复将被覆盖
*
* @param key 文件名,支持文件夹路径,例如:“QQ截图.png” 、 "/an111c/QQ截图.png",如果文件夹不存在腾讯云会自动创建
* @param file
* @return
*/
public Boolean put(String key, File file) {
try {
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
client.putObject(putObjectRequest);
} catch (Exception e) {
return false;
}
return true;
}
/**
* 上传文件到服务器 如果key重复将被覆盖
*
* @param key 文件名,支持文件夹路径,例如:“QQ截图.png” 、 "/an111c/QQ截图.png",如果文件夹不存在腾讯云会自动创建
* @param inputStream 直接 multipartFile.getInputStream()
* @return
*/
public Boolean put(String key, InputStream inputStream) {
try {
client.putObject(CosUtil.bucketName, key, inputStream, null);
} catch (Exception e) {
return false;
}
return true;
}
/**
* 判断对象是否已经存在
*
* @param key 文件名,支持文件夹路径,例如:“QQ截图.png” 、 "/an111c/QQ截图.png"
*/
public Boolean isExist(String key) {
return client.doesObjectExist(CosUtil.bucketName, key);
}
/**
* 获取带权限的下载链接
*
* @param key 文件名,支持文件夹路径,例如:“QQ截图.png” 、 "/an111c/QQ截图.png"
*/
public String getSourceUrl(String key) {
GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, key, HttpMethodName.GET);
// 设置签名过期时间(可选), 若未进行设置, 则默认使用 ClientConfig 中的签名过期时间(1小时)
Date expirationDate = new Date(System.currentTimeMillis() + expireTime * 1000L);
req.setExpiration(expirationDate);
return client.generatePresignedUrl(req).toString();
}
/**
* 上传文件MultipartFile转为File
*
* @param multipartFile
* @return
* @throws Exception
*/
public static File transferToFile(MultipartFile multipartFile) throws Exception {
//获取文件名,例如:QQ截图.png
String originalFilename = multipartFile.getOriginalFilename();
//获取文件后缀,例如:.png
String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
File file = File.createTempFile(originalFilename, prefix);
multipartFile.transferTo(file);
//在程序退出时,才会执行删除
file.deleteOnExit();
return file;
}
/**
* 获取上传文件的后缀,例如 .png
*
* @param multipartFile
* @return
* @throws Exception
*/
public static String getPrefix(MultipartFile multipartFile) {
//获取文件名,例如:QQ截图.png
String originalFilename = multipartFile.getOriginalFilename();
//获取文件后缀,例如:.png
String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
return prefix;
}
/**
* 获取上传文件的md5
* 32位小写
*
* @param multipartFile
* @return
* @throws Exception
*/
public static String getMd5(MultipartFile multipartFile) throws Exception {
//获取文件的byte信息
byte[] uploadBytes = multipartFile.getBytes();
//拿到一个MD5转换器
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] digest = md5.digest(uploadBytes);
//转换为16进制
return new BigInteger(1, digest).toString(16);
}
/**
* 获取文件大小
*
* @param file
* @param type 单位,1=KB,2=MB
* @return
*/
public static BigDecimal getFileSize(File file, int type) {
long size = file.length();
BigDecimal sizeDecimal = new BigDecimal(size);
BigDecimal kbDecimal = new BigDecimal(type == 1 ? "1024" : "1048576");
BigDecimal sizeKB = sizeDecimal.divide(kbDecimal, 2, BigDecimal.ROUND_HALF_UP);
return sizeKB;
}
/**
* 获取文件大小
*
* @param file
* @param type 单位,1=KB,2=MB
* @return
*/
public static BigDecimal getFileSize(MultipartFile file, int type) {
long size = file.getSize();
BigDecimal sizeDecimal = new BigDecimal(size);
BigDecimal kbDecimal = new BigDecimal(type == 1 ? "1024" : "1048576");
BigDecimal sizeKB = sizeDecimal.divide(kbDecimal, 2, BigDecimal.ROUND_HALF_UP);
return sizeKB;
}
}