广告
返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBoot整合腾讯云COS对象存储实现文件上传的示例代码
  • 176
分享到

SpringBoot整合腾讯云COS对象存储实现文件上传的示例代码

2024-04-02 19:04:59 176人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

目录1、开通腾讯云对象存储服务2、创建存储桶3、密钥管理,新建密钥4、yml配置密钥、COS信息5、COSConfig配置类6、COS文件上传工具类7、Controller测试上传接

企业级项目开发中都会有文件、图片、视频等文件上传并能够访问的场景,对于初学者Demo可能会直接存储在应用服务器上;对于传统项目可能会单独搭建FastDFS、MiNIO等文件服务来实现存储,这种方案可能对于企业成本较小,但缺点也是很多,例如:1、增加技术人员的运维和维护成本,2、规模越来越大时需要硬件的支持,且存在文件丢失风险,3、服务器没有CDN,用户访问网站图片加载慢用户体验不好。

所以,一般上规模的项目、或者追求用户体验的项目可能会考虑使用第三方的云服务来存储,市场主流厂商有:七牛云、阿里云OSS、腾讯云COS等,具体采用哪种存储方案需结合项目、规模、成本等因素,综合考量确定。

因为用的腾讯云服务器,为了方便统一管理,所以直接用了腾讯云的COS对象存储服务,下面是基于SpringBoot和腾讯云COS提供的Java SDK快速对接实现文件上传功能。

1、开通腾讯云对象存储服务

https://console.cloud.tencent.com/cos5

2、创建存储桶

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文件上传工具类



@Slf4j
public class COSClientUtil {
 
    
    private static COSConfig cosConfig = springBeanUtils.getBean(COSConfig.class);
 
    
    private static COSCredentials cred = new BasicCOSCredentials(cosConfig.getAccessKey(), cosConfig.getSecretKey());
 
    
    private static ClientConfig clientConfig = new ClientConfig(new Region(cosConfig.getRegionName()));
 
    
    private static COSClient cosClient = new COSClient(cred, clientConfig);
 
    
    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();
        }
    }
 
    
    private static String uploadFileToCOS(File localFile, String key) throws InterruptedException {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosConfig.getBucketName(), key, localFile);
        ExecutorService threadPool = Executors.newFixedThreadPool(8);
        // 传入一个threadPool, 若不传入线程池, 默认TransferManager中会生成一个单线程的线程池
        TransferManager transferManager = new TransferManager(cosClient, threadPool);
        // 返回一个异步结果Upload, 可同步的调用waitForUploadResult等待upload结束, 成功返回UploadResult, 失败抛出异常
        Upload upload = transferManager.upload(putObjectRequest);
        UploadResult uploadResult = upload.waitForUploadResult();
        transferManager.shutdownNow();
        cosClient.shutdown();
        String filePath = cosConfig.getBaseUrl() + uploadResult.getKey();
        return filePath;
    }
 
    
    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测试上传接口:


    
    @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接口调用

9、浏览器预览效果

到此这篇关于SpringBoot整合腾讯云COS对象存储实现文件上传的示例代码的文章就介绍到这了,更多相关SpringBoot腾讯云COS文件上传内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: SpringBoot整合腾讯云COS对象存储实现文件上传的示例代码

本文链接: https://www.lsjlt.com/news/160434.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作