首页 > 其他分享 >Spring Boot项目对接腾讯云COS对象存储上传文件接口

Spring Boot项目对接腾讯云COS对象存储上传文件接口

时间:2023-05-09 14:02:19浏览次数:35  
标签:COS String Spring Boot cos file new import com

Spring Boot项目对接腾讯云COS对象存储上传文件接口

pom.xml

<dependency>
    <groupId>com.qcloud</groupId>
    <artifactId>cos_api</artifactId>
    <version>5.6.35</version>
</dependency>

application.yml

cos:
  secretId: xxx
  secretKey: xxx
  bucketName: xxx-yyy #存储桶名称,格式一般是xxx-appId,比如cocktail-1300110000
  region: ap-xxx #地区,格式一般是ap-地区,比如上海:ap-shanghai

Service

import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 腾讯云对象存储cos服务类
 * @author Siemen_Xie
 */
public interface CosService {

    /**
     * 腾讯云对象存储上传图片
     * @param file 图片文件
     * @return 图片url
     */
    String uploadFile(MultipartFile file) throws IOException;
}

ServiceImpl

import cn.hutool.core.date.DateUtil;
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.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import com.ximen.cocktailserver.service.CosService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Date;
import java.util.UUID;

/**
 * @author Siemen_Xie
 */
@Service
public class CosServiceImpl implements CosService {

    @Value("${cos.secretId}")
    private String secretId;
    @Value("${cos.secretKey}")
    private String secretKey;
    @Value("${cos.bucketName}")
    private String bucketName;
    @Value("${cos.region}")
    private String region;

    /**
     * 上传文件到腾讯云cos
     *
     * @param file 上传的文件
     * @return 文件在cos上的访问url
     */
    @Override
    public String uploadFile(MultipartFile file) throws IOException {
//        if (file.getSize() <= 0) {
//            throw new RuntimeException("上传的文件大小不能为空");
//        }
//        if (file.getSize() > 20 * 1024 * 1024) {
//            throw new RuntimeException("上传的文件大小不能超过20MB");
//        }
//        if (!file.getContentType().startsWith("image")) {
//            throw new RuntimeException("上传的文件不是图片类型");
//        }
        // 初始化cos客户端
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        COSClient cosClient = new COSClient(cred, clientConfig);
        try {
            String oldName = file.getOriginalFilename();
            String suffix = oldName.substring(oldName.lastIndexOf(".") + 1);
            // 生成唯一文件名,当前时间 + 随机UUID + 文件类型
            String fileName = DateUtil.format(new Date(), "yyyyMMddHHmmss") + "-" + UUID.randomUUID() + "." + suffix;
            // 上传文件到cos
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(file.getSize());
            InputStream inputStream = file.getInputStream();
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, inputStream, metadata);
            cosClient.putObject(putObjectRequest);
            inputStream.close();
            // 返回文件在cos上的访问url
            return "https://" + bucketName + ".cos." + region + ".myqcloud.com/" + fileName;
        } catch (IOException e) {
            throw new RuntimeException("上传失败");
        } finally {
            // 关闭cos客户端
            cosClient.shutdown();
        }
    }
}

Controller

import com.ximen.cocktailserver.service.CosService;
import com.ximen.cocktailserver.utils.RestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 公共服务接口
 * @author Siemen_Xie
 */
@RestController
@RequestMapping("/api")
@Slf4j
public class PublicController {

    @Resource
    private CosService cosService;

    @PostMapping("/uploadFile")
    public RestResponse<String> uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        return RestResponse.ok(cosService.uploadFile(file));
    }

}

标签:COS,String,Spring,Boot,cos,file,new,import,com
From: https://www.cnblogs.com/ximensama/p/17384653.html

相关文章

  • Spring Boot 单体应用一键升级成 Spring Cloud Alibaba
    作者:十眠背景随着ApacheDubbo、Nacos以及SpringCloud等服务框架的流行,越来越多的企业开始采用微服务架构来构建其应用程序。微服务架构使企业能够将其应用程序拆分成多个小型服务,这些服务可以独立部署和扩展。这种架构模式也使企业更容易实现敏捷开发和持续交付,从而提高了......
  • COSC1076 Vending机器
    COSC1076|Semester12023AdvancedProgrammingTechniquesAssignment2VendingMachineAssessmentType:Bothgroupandindividualassessments.Weight:40%ofthefinalcoursemarkDueDate:23:59,Friday26May2023(Notethatthereisalsoagroupdemonstrat......
  • SpringBoot的@Configuration注解
    本文主要讲述SpringBoot的@Configuration注解。一.POJO类的声明例如有两个pojo类,分别是User和PetUser类的声明如下:publicclassUser{privateStringname;privateIntegerage;publicUser(){}publicUser(Stringname,Integer......
  • macOS下使用VS Code配置C/C++开发环境
      macOS系统中默认的C/C++编译器是clang/clang++,命令行使用gcc/g++或者clang/clang++来执行命令时,都是调用clang/clang++编译器,想使用gcc/g++编译器结合VSCode进行开发的话,我们可以自己安装。查看一下gcc和clang   1.安装Homebrew,官网链接,复制粘贴到Terminal运行脚......
  • Centos7安装nacos详细步骤(配置开机自启)
    Nacos解压文件创建数据库nacos,导入nacos的sql文件创建数据库nacos,导入nacos的sql文件修改启动文件(根据系统选择)[root@localhostbin]#cdnacos/bin/[root@localhostbin]#lsshutdown.cmdshutdown.shstartup.cmdstartup.sh[root@localhostbin]#vimstartu......
  • Spring注解开发报错
    今天学习Spring注解开发时,又报错了报错代码Exceptioninthread“main”org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException:Line6inXMLdocumentfromclasspathresource[1.xml]isinvalid;nestedexceptionisorg.xml.sax.SAXParseExceptio......
  • Springboot 项目配置 HTTPS
    生成证书输入命令keytool-genkeypair-alias"boot"-keyalg"RSA"-keystore"boot.keystore"生成完成后会提示Warning:JKS密钥库使用专用格式。建议使用"keytool-importkeystore-srckeystoreboot.keystore-destkeystoreboot.keystore-deststoretypepkc......
  • SpringBoot项目如何打包成exe应用程序?
    前言近期做了一个前后端合并的springboot项目,但是要求打包城exe文件,提供给不懂电脑的小白安装使用,就去研究了半天,踩了很多坑,写这篇文章,是想看到这篇文章的人,按照我的步骤走,能少踩坑。准备准备工作:一个jar包,没有bug能正常启动的jar包exe4j,一个将jar转换成exe的工具,链接:h......
  • [NSSCTF 2022 Spring Recruit]easy C
    C的源代码,查个壳:一般都是64位,直接双击吧,换个界面,成天看IDA也不好:也是简单的一个异或加密,上个脚本就好了,不多说啥:Des='d`vxbQd'flag=''foriinDes:flag+=chr((ord(i)^2)-1)print(flag)拿到NSSCTF......
  • 如何创建可引导的 ESXi USB 安装介质 (macOS, Linux, Windows)
    如何制作ESXiUSB启动盘请访问原文链接:https://sysin.org/blog/create-bootable-esxi-usb-installer/,查看最新版。原创作品,转载请保留出处。作者主页:sysin.org以下USB存储设备可以是U盘/SD卡,当然USBSSD更佳。macOSmacOS使用终端自带命令即可完成操作。查看US......