springboot上传图片至腾讯cos

去购买一个cos java

maven依赖

<dependencies>
      <!--因为写springcloud项目用到上传用到,此依赖可忽略-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        <version>0.9.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--核心依赖cos服务-->
    <dependency>
        <groupId>com.qcloud</groupId>
        <artifactId>cos_api</artifactId>
        <version>5.6.7</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <version>2.1.3.RELEASE</version>
    </dependency>
      <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>
复制代码

application.yml文件

server:
  port: 8082
spring:
  application:
    name: upload-service
  servlet:
    multipart:
      # 限制文件上传大小
      max-file-size: 10MB
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
qcloud:
  #初始化用户身份信息 前往控制台密钥管理查看
  secretId: ""
  secretKey: ""
  # 指定要上传到的存储桶
  bucketName: ""
  # 地区选择
  regionName: ""
复制代码

COSProperties类 用于读取yml/properties信息

/** * @Author :cjy * @description :cos配置属性类 使用ConfigurationProperties注解可将配置文件(yml/properties)中指定前缀的配置转为bean * @CreateTime :Created in 2019/9/8 23:39 */
@Data
@ConfigurationProperties(prefix = "qcloud")
public class COSProperties {
    // 初始化用户身份信息 前往密钥管理查看
    private   String secretId;
    // 初始化用户身份信息 前往密钥管理查看
    private String secretKey;
    // 指定要上传到的存储桶
    private String bucketName;
    //指定要上传的地区名称 去控制台查询
    private String regionName;
}

复制代码

建立COSClientConfig配置类,用于调用腾讯云cos接口

/** * @Author :cjy * @description :COSClient 是调用 COS API 接口的对象 * @CreateTime :Created in 2019/9/8 23:16 */
@Configuration
@EnableConfigurationProperties(COSProperties.class)
public class COSClientConfig {
    @Autowired
    private COSProperties cosProperties;

    @Bean
    public COSClient cosClient(){
        // 1 初始化用户身份信息(secretId, secretKey)。
// String secretId = "AKIDcKlIXWKgy3vc4Jj9tNblgW8UaPJxpZj8";
// String secretKey = "MUPecJmyuZzVs36vU8VeWLuCC5hPHxSS";
        COSCredentials cred = new BasicCOSCredentials(cosProperties.getSecretId(),cosProperties.getSecretKey());
        // 2 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region region = new Region(cosProperties.getRegionName());
        ClientConfig clientConfig = new ClientConfig(region);
        // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }
}

复制代码

UploadService类

/** * @Author :cjy * @description : * @CreateTime :Created in 2019/9/7 16:09 */
@Service
@Slf4j
public class UploadService {
    String key;

    @Autowired
    private COSClient cosClient;
    @Autowired
    private COSProperties cosProperties;

    // 支持的文件类型
    private static final List<String> suffixes = Arrays.asList("image/png", "image/jpeg");

    public String uploadImage(MultipartFile file) {

        try {
            // 一、图片信息校验
            // 1)校验文件类型
            String type = file.getContentType(); //获取文件格式
            if (!suffixes.contains(type)) {
                // logger.info("上传失败,文件类型不匹配:{}", type);
                return null;
            }
            // 2)校验图片内容
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null) {
               // logger.info("上传失败,文件内容不符合要求");
                return null;
            }

            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType(type);
            UUID uuid = UUID.randomUUID();
            // 指定要上传到 COS 上对象键 此key是文件惟一标识
            key = uuid.toString().replace("-","")+".jpg";
            PutObjectRequest putObjectRequest = new PutObjectRequest(cosProperties.getBucketName(), key, file.getInputStream(),objectMetadata);

            //使用cosClient调用第三方接口
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            log.info(putObjectRequest+"");
            //返回路径

        }catch (Exception e){
            e.printStackTrace();
        }
        //拼接返回路径
        String imagePath = "https://" + cosProperties.getBucketName() + ".cos." + cosProperties.getRegionName() + ".myqcloud.com/" + key;
        return imagePath;
    }
}

复制代码

UploadController 测试

@RestController
@RequestMapping("upload")
@Slf4j
public class UploadController {

    @Autowired
    private UploadService uploadService;

    /** * 上传图片 * @param file * @return */
    @PostMapping("image")
    public ResponseEntity<String> uploadImage(@RequestParam("file")MultipartFile file){

        String url=uploadService.uploadImage(file);
        log.info("返回地址:【{}】",url);
        return ResponseEntity.ok(url);
    }


}

复制代码

postman测试成功web

官方sdk文档: cloud.tencent.com/document/pr…
相关文章
相关标签/搜索