SpringBoot整合騰訊云COS對(duì)象存儲(chǔ)實(shí)現(xiàn)文件上傳的示例代碼
企業(yè)級(jí)項(xiàng)目開(kāi)發(fā)中都會(huì)有文件、圖片、視頻等文件上傳并能夠訪問(wèn)的場(chǎng)景,對(duì)于初學(xué)者Demo可能會(huì)直接存儲(chǔ)在應(yīng)用服務(wù)器上;對(duì)于傳統(tǒng)項(xiàng)目可能會(huì)單獨(dú)搭建FastDFS、MinIO等文件服務(wù)來(lái)實(shí)現(xiàn)存儲(chǔ),這種方案可能對(duì)于企業(yè)成本較小,但缺點(diǎn)也是很多,例如:1、增加技術(shù)人員的運(yùn)維和維護(hù)成本,2、規(guī)模越來(lái)越大時(shí)需要硬件的支持,且存在文件丟失風(fēng)險(xiǎn),3、服務(wù)器沒(méi)有CDN,用戶訪問(wèn)網(wǎng)站圖片加載慢用戶體驗(yàn)不好。
所以,一般上規(guī)模的項(xiàng)目、或者追求用戶體驗(yàn)的項(xiàng)目可能會(huì)考慮使用第三方的云服務(wù)來(lái)存儲(chǔ),市場(chǎng)主流廠商有:七牛云、阿里云OSS、騰訊云COS等,具體采用哪種存儲(chǔ)方案需結(jié)合項(xiàng)目、規(guī)模、成本等因素,綜合考量確定。
因?yàn)橛玫尿v訊云服務(wù)器,為了方便統(tǒng)一管理,所以直接用了騰訊云的COS對(duì)象存儲(chǔ)服務(wù),下面是基于SpringBoot和騰訊云COS提供的Java SDK快速對(duì)接實(shí)現(xiàn)文件上傳功能。
1、開(kāi)通騰訊云對(duì)象存儲(chǔ)服務(wù)
https://console.cloud.tencent.com/cos5
2、創(chuàng)建存儲(chǔ)桶
3、密鑰管理,新建密鑰
4、yml配置密鑰、COS信息
cos: baseUrl: fxxxxxa-1xxxxx1.cos.ap-shanghai.myqcloud.com accessKey: AKxxxxxxxxxxxxxxxxxxxxxxxxxCF secretKey: oKxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxni regionName: ap-shanghai bucketName: fxxxxxa-1xxxxx1 folderPrefix: /files
5、COSConfig配置類
@Data @Component @ConfigurationProperties(prefix = "cos") public class COSConfig { private String baseUrl; private String accessKey; private String secretKey; private String regionName; private String bucketName; private String folderPrefix; }
6、COS文件上傳工具類
/** * 騰訊云COS文件上傳工具類 */ @Slf4j public class COSClientUtil { /** * 獲取配置信息 */ private static COSConfig cosConfig = SpringBeanUtils.getBean(COSConfig.class); /** * 初始化用戶身份信息 */ private static COSCredentials cred = new BasicCOSCredentials(cosConfig.getAccessKey(), cosConfig.getSecretKey()); /** * 設(shè)置bucket的區(qū)域 */ private static ClientConfig clientConfig = new ClientConfig(new Region(cosConfig.getRegionName())); /** * 生成COS客戶端 */ private static COSClient cosClient = new COSClient(cred, clientConfig); /** * 上傳文件 * * @param file * @return * @throws Exception */ public static String upload(MultipartFile file) throws Exception { String date = DateUtils.formateDate(new Date(), "yyyy-MM-dd"); String originalFilename = file.getOriginalFilename(); long nextId = IdGenerator.getFlowIdWorkerInstance().nextId(); String name = nextId + originalFilename.substring(originalFilename.lastIndexOf(".")); String folderName = cosConfig.getFolderPrefix() + "/" + date + "/"; String key = folderName + name; File localFile = null; try { localFile = transferToFile(file); String filePath = uploadFileToCOS(localFile, key); log.info("upload COS successful: {}", filePath); return filePath; } catch (Exception e) { throw new Exception("文件上傳失敗"); } finally { localFile.delete(); } } /** * 上傳文件到COS * * @param localFile * @param key * @return */ private static String uploadFileToCOS(File localFile, String key) throws InterruptedException { PutObjectRequest putObjectRequest = new PutObjectRequest(cosConfig.getBucketName(), key, localFile); ExecutorService threadPool = Executors.newFixedThreadPool(8); // 傳入一個(gè)threadPool, 若不傳入線程池, 默認(rèn)TransferManager中會(huì)生成一個(gè)單線程的線程池 TransferManager transferManager = new TransferManager(cosClient, threadPool); // 返回一個(gè)異步結(jié)果Upload, 可同步的調(diào)用waitForUploadResult等待upload結(jié)束, 成功返回UploadResult, 失敗拋出異常 Upload upload = transferManager.upload(putObjectRequest); UploadResult uploadResult = upload.waitForUploadResult(); transferManager.shutdownNow(); cosClient.shutdown(); String filePath = cosConfig.getBaseUrl() + uploadResult.getKey(); return filePath; } /** * 用緩沖區(qū)來(lái)實(shí)現(xiàn)這個(gè)轉(zhuǎn)換, 即創(chuàng)建臨時(shí)文件 * 使用 MultipartFile.transferTo() * * @param multipartFile * @return */ private static File transferToFile(MultipartFile multipartFile) throws IOException { String originalFilename = multipartFile.getOriginalFilename(); String prefix = originalFilename.split("\\.")[0]; String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")); File file = File.createTempFile(prefix, suffix); multipartFile.transferTo(file); return file; } }
7、Controller測(cè)試上傳接口:
/** * 騰訊云COS上傳 * * @param file * @return * @throws Exception */ @PostMapping(value = "/cosUpload") public ResponseEntity cosUpload(MultipartFile file) throws Exception { String filePath = COSClientUtil.upload(file); UploadDTO dto = UploadDTO.builder().filePath(filePath).build(); return ResultVOUtil.success(dto); }
8、PostMan接口調(diào)用
9、瀏覽器預(yù)覽效果
到此這篇關(guān)于SpringBoot整合騰訊云COS對(duì)象存儲(chǔ)實(shí)現(xiàn)文件上傳的示例代碼的文章就介紹到這了,更多相關(guān)SpringBoot騰訊云COS文件上傳內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot使用Minio進(jìn)行文件存儲(chǔ)的實(shí)現(xiàn)
- SpringBoot中整合Minio文件存儲(chǔ)的安裝部署過(guò)程
- Springboot集成minio實(shí)現(xiàn)文件存儲(chǔ)的實(shí)現(xiàn)代碼
- SpringBoot 使用Mongo的GridFs實(shí)現(xiàn)分布式文件存儲(chǔ)操作
- springboot臨時(shí)文件存儲(chǔ)目錄配置方式
- SpringBoot整合阿里云OSS對(duì)象存儲(chǔ)服務(wù)實(shí)現(xiàn)文件上傳
- Spring File Storage文件的對(duì)象存儲(chǔ)框架基本使用小結(jié)
相關(guān)文章
Java 解決讀寫(xiě)本地文件中文亂碼的問(wèn)題
這篇文章主要介紹了Java 解決讀寫(xiě)本地文件中文亂碼的問(wèn)題的相關(guān)資料,需要的朋友可以參考下2017-01-01詳解Spring Boot 中實(shí)現(xiàn)定時(shí)任務(wù)的兩種方式
這篇文章主要介紹了Spring Boot 中實(shí)現(xiàn)定時(shí)任務(wù)的兩種方式,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04如何把char數(shù)組轉(zhuǎn)換成String
這篇文章主要介紹了如何把char數(shù)組轉(zhuǎn)換成String問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02簡(jiǎn)單了解Spring循環(huán)依賴解決過(guò)程
這篇文章主要介紹了簡(jiǎn)單了解Spring循環(huán)依賴解決過(guò)程,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11java對(duì)象數(shù)組實(shí)現(xiàn)學(xué)生信息管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了java對(duì)象數(shù)組實(shí)現(xiàn)學(xué)生信息管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-06-06