1、導入相關依賴
<!--騰訊云COS-->
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>5.6.8</version>
</dependency>
2、編寫配置類,獲取配置信息
創(chuàng)建配置類主要需要以下信息
騰訊云賬號秘鑰和密碼秘鑰:用于創(chuàng)建COSClient鏈接對象,識別用戶身份信息
存儲桶區(qū)域:需要設置客戶端所屬區(qū)域Region
存儲桶名稱:創(chuàng)建請求時,需要告知上傳到哪個存儲桶下
存儲桶訪問路徑:用于拼裝上傳文件完整訪問路徑
我獲得的信息均寫在配置類中,這里使用?@Value?或者 @ConfigurationProperties?都可以,寫法就不多說,但是注意?@ConfigurationProperties 支持松散綁定,在識別讀取配置信息時,不區(qū)分大小寫,且會去掉中劃線-、下劃線_ (A-b_Obj→abobj→abObj),參考:SpringBoot松散綁定(寬松綁定)@ConfigurationProperties
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.region.Region;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
/**
* @author phf
* @description @ConfigurationProperties 松散綁定(中劃線-、下劃線_ 都去掉,且不區(qū)分大小寫)
*/
@Component
@ConfigurationProperties(prefix = "cos")
@Data
public class CosConfig {
/**
* 騰訊云賬號秘鑰
*/
private String secretId;
/**
* 密碼秘鑰
*/
private String secretKey;
/**
* 存儲桶地區(qū)
*/
private String region;
/**
* 存儲桶名稱
*/
private String bucketName;
/**
* 存儲桶訪問路徑
*/
private String path;
/**
* 初始化cos對象,配置相關配置信息
*/
@Bean
public COSClient cosClient(){
// 1 初始化用戶身份信息(secretId, secretKey)。
COSCredentials cred = new BasicCOSCredentials(this.secretId, this.secretKey);
// 2 設置 bucket 的區(qū)域
Region region = new Region(this.region);
ClientConfig clientConfig = new ClientConfig(region);
// 3 生成 cos 客戶端。
COSClient cosClient = new COSClient(cred, clientConfig);
return cosClient;
}
}
配置信息獲取
(1)進入騰訊云對象存儲→創(chuàng)建存儲桶(有則跳過),獲取存儲桶名稱、區(qū)域、存儲桶訪問路徑
(2)獲取騰訊云賬號秘鑰
3、編寫邏輯層——實現(xiàn)上傳
我這里用了多文件上傳,單文件上傳,把數(shù)組和循環(huán)去掉即可
public interface ICosFileService {
/**
* 上傳
* @param files
* @return
*/
RestApiResponse<String> upload(MultipartFile[] files);
/**
* 刪除
* @param fileName
* @return
*/
RestApiResponse<Void> delete(String fileName);
}
@Slf4j
@Service
public class ICosFileServiceImpl implements ICosFileService {
@Resource
private COSClient cosClient;
@Resource
private CosConfig cosConfig;
@Override
@Transactional(rollbackFor = Exception.class)
public RestApiResponse<String> upload(MultipartFile[] files) {
RestApiResponse<String> response = RestApiResponse.success();
String res = "";
try {
for (MultipartFile file : files) {
String originalFileName = file.getOriginalFilename();
// 獲得文件流
InputStream inputStream = null;
inputStream = file.getInputStream();
// 設置文件路徑
String filePath = getFilePath(originalFileName, "你的桶內文件路徑abc/def/test/");
// 上傳文件
String bucketName = cosConfig.getBucketName();
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(file.getSize());
objectMetadata.setContentType(file.getContentType());
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filePath, inputStream, objectMetadata);
cosClient.putObject(putObjectRequest);
cosClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
String url = cosConfig.getPath() + "/" + filePath;
res += url + ",";
}
String paths = res.substring(0, res.length() - 1);
response.setData(paths);
return response;
} catch (IOException e) {
e.printStackTrace();
} finally {
cosClient.shutdown();
}
return RestApiResponse.fail();
}
@Override
public RestApiResponse<Void> delete(String fileName) {
cosConfig.cosClient();
// 文件桶內路徑
String filePath = getDelFilePath(fileName, "你的桶內文件路徑abc/def/test/");
cosClient.deleteObject(cosConfig.getBucketName(), filePath);
return RestApiResponse.success();
}
/**
* 生成文件路徑
* @param originalFileName 原始文件名稱
* @param folder 存儲路徑
* @return
*/
private String getFilePath(String originalFileName, String folder) {
// 獲取后綴名
String fileType = originalFileName.substring(originalFileName.lastIndexOf("."));
// 以文件后綴來存儲在存儲桶中生成文件夾方便管理
String filePath = folder + "/";
// 去除文件后綴 替換所有特殊字符
String fileStr = StrUtil.removeSuffix(originalFileName, fileType).replaceAll("[^0-9a-zA-Z\\u4e00-\\u9fa5]", "_");
filePath += new DateTime().toString("yyyyMMddHHmmss") + "_" + fileStr + fileType;
log.info("filePath:" + filePath);
return filePath;
}
/**
* 生成文件路徑
* @param originalFileName 原始文件名稱
* @param folder 存儲路徑
* @return
*/
private String getDelFilePath(String originalFileName, String folder) {
// 獲取后綴名
String fileType = originalFileName.substring(originalFileName.lastIndexOf("."));
// 以文件后綴來存儲在存儲桶中生成文件夾方便管理
String filePath = folder + "/";
// 去除文件后綴 替換所有特殊字符
String fileStr = StrUtil.removeSuffix(originalFileName, fileType).replaceAll("[^0-9a-zA-Z\\u4e00-\\u9fa5]", "_");
filePath += fileStr + fileType;
log.info("filePath:" + filePath);
return filePath;
}
}
?4、編寫Controller測試
@Api(tags = "cos文件操作")
@RestController
@RequestMapping("/cos")
public class ICosFileController {
@Autowired
private ICosFileService iCosFileService;
@ApiOperation(value = "文件上傳", httpMethod = "POST")
@PostMapping("/upload")
public RestApiResponse<String> upload(@RequestParam("files") MultipartFile[] files) {
RestApiResponse<String> result = iCosFileService.upload(files);
return result;
}
@ApiOperation(value = "文件刪除", httpMethod = "POST")
@PostMapping("/delete")
public RestApiResponse<String> delete(@RequestParam("fileName") String fileName) {
iCosFileService.delete(fileName);
return RestApiResponse.success();
}
}
上傳成功,且返回完整信息
刪除時,保證刪除的文件名稱參數(shù)key,為桶內文件完整路徑即可,如果你的桶是app-bucket-name,文件含桶路徑是app-bucket-name/file1/file2/file.png,那桶內完整路徑就是file1/file2/file.png
public RestApiResponse<Void> delete(String fileName) {
cosConfig.cosClient();
// 文件桶內路徑
String filePath = getDelFilePath(fileName, "你的桶內文件路徑abc/def/test/");
// 這里的第二個參數(shù),必須是桶內的完整路徑
cosClient.deleteObject(cosConfig.getBucketName(), filePath);
return RestApiResponse.success();
}
5、問題:COSClient報錯連接池已關閉
之前自主調用了cosClient.shutdown,結果第二次上傳時,就拋出異常,其實它自己維護了一個線程池:對象存儲 Java SDK 常見問題-SDK 文檔-文檔中心-騰訊云
?文章來源:http://www.zghlxwxcb.cn/news/detail-609428.html
6、完整代碼
https://download.csdn.net/download/huofuman960209/88085303文章來源地址http://www.zghlxwxcb.cn/news/detail-609428.html
到了這里,關于springboot快速整合騰訊云COS對象存儲的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!