1.申请腾讯云存储桶
新建密钥(后面配置要用到)
2.编写工具类
此处使用工具类进行基本属性配置,也可选择在yml中配置文章来源:https://www.toymoban.com/news/detail-814477.html
package com.sfy.util;
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.PutObjectRequest;
import com.qcloud.cos.region.Region;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.Random;
public class TencentCOSUploadFileUtil {
// 存储桶名称
private static final String BUCKET_NAME = "";
//secretId 秘钥id
private static final String SECRET_ID = "";
//SecretKey 秘钥
private static final String SECRET_KEY = "";
// 腾讯云 自定义文件夹名称
private static final String PREFIX = "";
// 访问域名
public static final String URL = "";
// 创建COS 凭证
private static final COSCredentials credentials = new BasicCOSCredentials(SECRET_ID,SECRET_KEY);
// 配置 COS 区域 就购买时选择的区域
private static final ClientConfig clientConfig = new ClientConfig(new Region("ap-nanjing"));
/**
* @methodName uploadfile
* @effect: 上传文件
*/
public static String uploadfile(MultipartFile file){
// 创建 COS 客户端连接
COSClient cosClient = new COSClient(credentials,clientConfig);
String fileName = file.getOriginalFilename();
try {
assert fileName != null;
String substring = fileName.substring(fileName.lastIndexOf("."));
File localFile = File.createTempFile(String.valueOf(System.currentTimeMillis()),substring);
file.transferTo(localFile);
Random random = new Random();
fileName =PREFIX+random.nextInt(10000)+System.currentTimeMillis()+substring;
// 将 文件上传至 COS
PutObjectRequest objectRequest = new PutObjectRequest(BUCKET_NAME,fileName,localFile);
cosClient.putObject(objectRequest);
}catch (Exception e){
e.printStackTrace();
}finally {
cosClient.shutdown();
}
return URL+fileName;
}
}
文章来源地址https://www.toymoban.com/news/detail-814477.html
3.controller层
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("/uploadFile")
public class UploadFileController {
@RequestMapping("upload")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file){
if (null == file) {
return "文件为空";
}
String filePath = TencentCOSUploadFileUtil.uploadfile(file);
return "上传成功,访问地址为:"+filePath;
}
}
到了这里,关于springboot集成COS对象存储的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!