package com.hx.util; import com.aliyun.oss.OSSClient; import com.aliyun.oss.model.OSSObject; 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.PutObjectRequest; import com.qcloud.cos.model.PutObjectResult; import com.qcloud.cos.region.Region; import org.springframework.web.multipart.MultipartFile; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Date; /**腾讯云 COS * @author ChenJiaHe * @date 2020-12-03 */ public class COSUtil { /** 后端调用上传图片 * @param key 上传路径(包括图片名称和和后缀),指定要上传到 COS 上对象键 * @param localFile * @param secretId 用户id * @param secretKey 用户秘钥 * @param regionName 存在域,参考腾讯云 * @param bucketName 指定要上传到的存储桶 * @return * @throws IOException */ public static String uploadImg(String key,MultipartFile localFile,String secretId, String secretKey,String regionName,String bucketName) throws IOException { // 1 初始化用户身份信息(secretId, secretKey)。 COSCredentials cred = new BasicCOSCredentials(secretId, secretKey); // 2 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224 // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。 Region region = new Region(regionName); ClientConfig clientConfig = new ClientConfig(region); // 3 生成 cos 客户端。 COSClient cosClient = new COSClient(cred, clientConfig); //开始上传 ObjectMetadata objectMetadata = new ObjectMetadata(); // 设置输入流长度为500 objectMetadata.setContentLength(localFile.getSize()); // 设置 Content type, 默认是 application/octet-stream,对于本地文件上传,默认根据本地文件的后缀进行映射 // ,例如 jpg 文件映射 为image/jpeg对于流式上传 默认是 application/octet-stream //objectMetadata.setContentType("application/pdf"); PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key,localFile.getInputStream(),objectMetadata); PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest); //拼接路径 StringBuilder imgUrl = new StringBuilder(); imgUrl.append("https://"+bucketName+".cos."+regionName+".myqcloud.com"); if(key.startsWith("/")){ imgUrl.append(key); }else{ imgUrl.append("/"+key); } return imgUrl.toString(); } }