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.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.regex.admin.common.util.PropertiesUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.URL;
import java.text.MessageFormat;
import java.util.Date;
import java.util.Random;
/**
* COSBrowser工具
*
* @author yuanxiyang
* @date 2020/07/07
*/
public class CosManage {
private static final Logger logger = LoggerFactory.getLogger(CosManage.class);
//创建cos客户端消耗大,故单例
public static final CosManage INSTANCE = new CosManage();
private PropertiesUtils propertiesUtils = new PropertiesUtils("properties/setting-web.properties");
//桶名称
private String bucketName = propertiesUtils.readProperty("cosBucketName");
//secretId
private String secretId = propertiesUtils.readProperty("cosSecretId");
// secretKey
private String secretKey = propertiesUtils.readProperty("cosSecretKey");
// 地域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
private String regionName = propertiesUtils.readProperty("cosRegionName");
// 云存储目录
private String cosFileDir = propertiesUtils.readProperty("cosFileDir");
private COSClient cosClient;
private CosManage() {
init();
}
//cos云存储客户端初始化
private void init() {
// 1 初始化用户身份信息(secretId, secretKey)
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 2 设置bucket的区域
ClientConfig clientConfig = new ClientConfig(new Region(regionName));
// 3 生成cos客户端
COSClient cosClient = new COSClient(cred, clientConfig);
this.cosClient = new COSClient(cred, clientConfig);
}
/**
* 销毁
*/
public void destory() {
cosClient.shutdown();
}
/**
* 将本地图片上传到云
*
* @param path 本地文件路径
* @return url
*/
public String uploadImg2Cos(String path) throws Exception {
File fileOnServer = new File(path);
FileInputStream fis;
String url = "";
try {
fis = new FileInputStream(fileOnServer);
String[] split = path.split("/");
url = uploadFile2Cos(fis, split[split.length - 1]);
} catch (FileNotFoundException e) {
logger.error("文件:" + path + "不存在", e);
}
return url;
}
/**
* 将本地图片上传到云
*
* @param file 用户上传的文件,通常在控制器中接收
* @return url
*/
public String uploadFile2Cos(MultipartFile file) throws Exception {
//腾讯云官方文档说明不建议上传20M以上文件
if (file.getSize() > 20 * 1024 * 1024) {
throw new Exception("上传图片大小不能超过20M!");
}
//文件名 demo.jpg
String originalFilename = file.getOriginalFilename();
//文件后缀 .jpg
String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
Random random = new Random();
//拼一个文件名
String name = random.nextInt(10000) + System.currentTimeMillis() + suffix;
try {
InputStream inputStream = file.getInputStream();
return uploadFile2Cos(inputStream, name);
} catch (Exception e) {
throw new Exception("图片上传失败");
}
}
/**
* 获得图片路径
*
* @param fileUrl
* @return
*/
public String getImgUrl(String fileUrl) {
return getUrl(fileUrl);
}
/**
* 获得url链接
*
* @param key
* @return
*/
public String getUrl(String key) {
// 设置URL过期时间为10年 3600l* 1000*24*365*10
Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
// 生成URL
URL url = cosClient.generatePresignedUrl(bucketName, key, expiration);
if (url != null) {
return url.toString();
}
return null;
}
/**
* 上传到COS服务器 如果同名文件会覆盖服务器上的
*
* @param ins 文件流
* @param key 文件名称 包括后缀名
* @return 返回云链接url,出错返回""
*/
public String uploadFile2Cos(InputStream ins, String key) {
String url = "";
try {
// 创建上传Object的Metadata
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(ins.available());
objectMetadata.setCacheControl("no-cache");
objectMetadata.setHeader("Pragma", "no-cache");
objectMetadata.setContentType(getcontentType(key.substring(key.lastIndexOf("."))));
objectMetadata.setContentDisposition("inline;filename=" + key);
// 上传文件
cosClient.putObject(bucketName, cosFileDir + key, ins, objectMetadata);
//拼接外链路径
url = MessageFormat.format("http://{0}.cos.{1}.myqcloud.com/{2}{3}", bucketName, regionName, cosFileDir, key);
} catch (IOException e) {
logger.error("图片上传失败", e);
} finally {
try {
if (ins != null) {
ins.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return url;
}
/**
* 判断Cos服务文件上传时文件的contentType
*
* @param fileSuffix 文件后缀
* @return String
*/
private String getcontentType(String fileSuffix) {
if (fileSuffix.equalsIgnoreCase("bmp")) {
return "image/bmp";
}
if (fileSuffix.equalsIgnoreCase("gif")) {
return "image/gif";
}
if (fileSuffix.equalsIgnoreCase("jpeg") || fileSuffix.equalsIgnoreCase("jpg")
|| fileSuffix.equalsIgnoreCase("png")) {
return "image/jpeg";
}
if (fileSuffix.equalsIgnoreCase("html")) {
return "text/html";
}
if (fileSuffix.equalsIgnoreCase("txt")) {
return "text/plain";
}
if (fileSuffix.equalsIgnoreCase("vsd")) {
return "application/vnd.visio";
}
if (fileSuffix.equalsIgnoreCase("pptx") || fileSuffix.equalsIgnoreCase("ppt")) {
return "application/vnd.ms-powerpoint";
}
if (fileSuffix.equalsIgnoreCase("docx") || fileSuffix.equalsIgnoreCase("doc")) {
return "application/msword";
}
if (fileSuffix.equalsIgnoreCase("xml")) {
return "text/xml";
}
return "image/jpeg";
}
}
PropertiesUtils.java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
public class PropertiesUtils {
private String properiesName = "properties/sysConfig.properties";
public PropertiesUtils() {
}
public PropertiesUtils(String fileName) {
this.properiesName = fileName;
}
public String readProperty(String key) {
String value = "";
InputStream is = null;
try {
is = PropertiesUtils.class.getClassLoader().getResourceAsStream(
properiesName);
Properties p = new Properties();
p.load(is);
value = p.getProperty(key);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if(is!=null)
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return value;
}
public Properties getProperties() {
Properties p = new Properties();
InputStream is = null;
try {
is = PropertiesUtils.class.getClassLoader().getResourceAsStream(
properiesName);
p.load(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return p;
}
public void writeProperty(String key, String value) {
InputStream is = null;
OutputStream os = null;
Properties p = new Properties();
try {
is = new FileInputStream(properiesName);
p.load(is);
os = new FileOutputStream(PropertiesUtils.class.getClassLoader().getResource(properiesName).getFile());
p.setProperty(key, value);
p.store(os, key);
os.flush();
os.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (null != is)
is.close();
if (null != os)
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
记一个坑
腾讯云的cos_api中依赖httpclient
在httpclient 为4.4.1版本时,创建COSClient会失败
要么通过升级httpclient版本,要么通过降低cos版本(当时是升级了httpclient版本解决)