说明:项目开发中,需要上传文件到腾讯云上,所有就开始研究了下腾讯云。
一.首先,打开官网,注册账号
链接: https://cloud.tencent.com/. 查一下必备参数 用户->账号信息->APPID 即可查看APPID 因为我这里想自己尝试下,不够买的话,没法创建存储桶,所以我这里实名认证了一下,并且购买了服务器,这样自己开发起来方便,直观看到存储上的文件,有需要的可以考虑,我想着也不贵,就尝试了下。 接下来是购买的过程: 云产品-对象存储 这个时候就可以创建存储桶,到时候上传的文件会上传到 存储桶里
这样存储桶就创建好了。== 存储桶名称后面配置会用,留意一下==。 这样在存储桶列表,即可查看。 点击上图 ->配置管理 这里参数注意一下,后面要用到 点击进来即可看到,这些参数后面配置会用到,留意一下。
二.步入开发正题,前面都是铺垫
1.首先,导入JAR包
参考文档: https://www.freesion.com/article/86731291045/.
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>5.6.8</version>
</dependency>
2.配置文件中增加腾讯云COS的配置
如下: 查看自己的appId和secretId,secretKey bucket-name是自己的存储桶名称,region-id值得是所属地域 base-url值得是你最终上传到cos上之后,返回的临时下载链接或者对象地址,有一个固定的url 上面都有这些参数的对应位置查找,自行查找一下。
3.JAVA代码
1.配置文件yml中cos配置对应的类
package com.office.dto;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.io.Serializable;
@Data
@Component
@ConfigurationProperties(prefix = "tencent.cos")
public class TencentCos implements Serializable {
private String appId;
private String secretId;
private String secretKey;
private String bucketName;
private String regionId;
private String baseUrl;
}
2.编写config,获取CosClient
我这里是什么 图片 pdf… 等,都可上传,就没像上述文档一样
package com.office.config;
import com.office.dto.TencentCos;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "tencent")
public class TencentCosConfig {
public static final String COS_ATTACHMENT = "attachment";
@Autowired
private TencentCos tencentCos;
@Bean
@Qualifier(COS_ATTACHMENT)
@Primary
public COSClient getCoSClient(){
//初始化用户身份信息
BasicCOSCredentials cosCredentials = new BasicCOSCredentials(tencentCos.getSecretId(), tencentCos.getSecretKey());
//设置bucket区域
//clientConfig中包含了设置region
ClientConfig clientConfig = new ClientConfig(new Region(tencentCos.getRegionId()));
//生成cos客户端
COSClient cosClient = new COSClient(cosCredentials, clientConfig);
return cosClient;
}
}
3.对应的上传文件的controller中,新增接口
@Autowired
private TencentCos tencentCos;
@Resource
private TencentCosConfig tencentCosConfig;
@Value("${tencent.cos.bucket-name}")
private String bucketName;
@RequestMapping(value = "/uploadFileTencentCos",method = RequestMethod.POST)
public ResultObject getUploadFileTencentCosUrl(@RequestParam("multipartFile") MultipartFile multipartFile) throws SystemException, UploadException {
ResultObject result = ResultObject.createInstance();
//判断文件不为空
if (ObjectUtils.isEmpty(multipartFile) || multipartFile.getSize()<=0){
throw new SystemException("未指定文件!");
}
File localFile = null;
String originalFilename = null;
String[] filename = null;
try {
originalFilename = multipartFile.getOriginalFilename();
logger.info("fileName = {}",originalFilename);
filename = originalFilename.split("\\.");
localFile = File.createTempFile(filename[0], filename[1]);
//将localFile这个文件所指向的文件 上传到对应的目录
multipartFile.transferTo(localFile);
localFile.deleteOnExit();
} catch (IOException e) {
e.printStackTrace();
logger.info("MultipartFile transfer file IOException ={}",e.getMessage());
//文件上传失败就返回错误响应
throw new UploadException("上传失败!");
}
if(localFile == null){
throw new UploadException("临时文件为空!");
}
//2.【将文件上传到腾讯云】
// PutObjectRequest(参数1,参数2,参数3)参数1:存储桶,参数2:指定腾讯云的上传文件路径,参数3:要上传的文件
String key = TencentCosConfig.COS_ATTACHMENT + "/" + new Date().getTime() + "." +filename[1];
//String key = baseUrl + "/" + originalFilename;
logger.info("key = {}", key);
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
//设置存储类型 默认标准型
putObjectRequest.setStorageClass(StorageClass.Standard);
//获得到客户端
COSClient cosClient = tencentCosConfig.getCoSClient();
try {
PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
//putObjectResult 会返回etag
String eTag = putObjectResult.getETag();
logger.info("eTag = {}", eTag);
} catch (CosServiceException e) {
logger.error("CosServiceException ={}", e.getMessage());
throw new CosServiceException(e.getMessage());
} catch (CosClientException e) {
logger.error("CosClientException ={}", e.getMessage());
throw new CosClientException(e.getMessage());
}
cosClient.shutdown();
String url = tencentCos.getBaseUrl() + "/" + key;
logger.info("上传路径:"+url);
HashMap<String, Object> map = new HashMap<>();
map.put("originFileName",originalFilename);
String[] newFileName = key.split("/");
map.put("newFileName",newFileName[1]);
map.put("filePath",url);
result.setData(map);
return result;
}
这里我自己创建了个 UploadException 异常。
4.返回参数
{
"success": true,
"message": "成功",
"data": {
"originFileName": "火星图片.jpg",
"filePath": "https://存储桶名称.cos.ap-nanjing.myqcloud.com/attachment/1650531205870.jpg",
"newFileName": "1650531205870.jpg"
},
"errorfield": null,
"msginfo": null
}
最后,在腾讯云即可查看上传的文件。 欢迎留言!
|