欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

使用Springboot实现腾讯云对象存储COS的文件上传:完整流程、详细步骤和代码实现

最编程 2024-01-03 18:53:58
...

腾讯云对象存储COS,Springboot实现文件上传

操作步骤:
1.注册腾讯云账号,开启对象存储服务
2.编写程序,实现文件上传

1.注册账号

1.注册一个账号,直接微信扫码即可,可实名认证

在这里插入图片描述

2.点击存储与网络,选择对象存储服务(这里有免费体验的可以选择)

在这里插入图片描述

3.创建存储桶

在这里插入图片描述

4.修改名称,修改访问权限

在这里插入图片描述

5.剩下的都不用动,点击下一步即可

在这里插入图片描述
在这里插入图片描述

6.创建好了之后点击概览,记录存储桶名称,所属地域,和访问域名(后边编写程序要用)

在这里插入图片描述

7.进入密钥管理,访问密钥

在这里插入图片描述

8.新建密钥,记住id和key(写程序要用)

在这里插入图片描述--------------------------------------------------------------------分割线------------------------------------------------------------------

2.编写程序实现文件上传

1.编写yml配置文件

#腾讯云COS配置
tencent:
  cos:
  	#访问域名
    rootSrc : https://tenc*********9516.cos.ap-nanjing.myqcloud.com
    #所属地域
    bucketAddr: ap-nanjing
    SecretId: AKIDq*******MSIuFKAk5A0oNfiV
    SecretKey: eZLr89*******GBrIXaP0MVRBnESUN
    #存储桶名称
    bucketName: tence*********8349516

2.编写腾讯云连接配置类

实现思路:
1.引用lombok依赖使用@Data注解自动生成getter和setter注解
2.使用@Component注解控制反转
3.使用配置类注解@ConfigurationProperties注入外部配置类属性

package com.itheima.utils;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(prefix = "tencent.cos")
public class TencentCOSproperties {
    private String rootSrc ; // https://tence**********349516.cos.ap-nanjing.myqcloud.com
    private String bucketAddr; // ap-nanjing
    private String SecretId; // AKIDqa9Bz**********KAk5A0oNfiV
    private String SecretKey; // eZLr89**********IXaP0MVRBnESUN
    private String bucketName; // tencen**********8349516
}

3.编写文件上传工具类

实现思路(具体实现步骤见注解):
1.依赖注入@Autowired获得腾讯云的属性参数
2.参考腾讯云快速入门手册获取 COSClient 类客户端对象
3.实现文件上传

在执行任何和 COS 服务相关请求之前,都需要先生成 COSClient 类的对象, COSClient 是调用 COS API 接口的对象。

package com.itheima.utils;

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.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;


import java.io.InputStream;
import java.util.UUID;
//交给IOC容器管理
@Component
public class TencentCOSUtils {

    @Autowired
    private TencentCOSproperties tencentCOSproperties;


    public String upload(MultipartFile file) throws Exception {
        //获取客户端
        // 1 初始化用户身份信息(secretId, secretKey)。
        COSCredentials cred = new BasicCOSCredentials
                (tencentCOSproperties.getSecretId(), tencentCOSproperties.getSecretKey());
        // 2 设置存储桶的地域(上文获得)
        Region region = new Region(tencentCOSproperties.getBucketAddr());
        ClientConfig clientConfig = new ClientConfig(region);
        // 3 使用https协议传输
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 4 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);


        // 获取上传的文件的输入流
        InputStream inputStream = file.getInputStream();
        // 避免文件覆盖,获取文件的原始名称,如123.jpg,然后通过截取获得文件的后缀,也就是文件的类型
        String originalFilename = file.getOriginalFilename();
        // 获取文件的类型
        String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 使用UUID工具  创建唯一名称,放置文件重名被覆盖,在拼接上上命令获取的文件类型
        String fileName = UUID.randomUUID().toString() + fileType;
        // 指定文件上传到 COS 上的路径,即对象键。最终文件会传到存储桶名字中的images文件夹下的fileName名字
        String key = "images/" + fileName;
        // 创建上传Object的Metadata
        ObjectMetadata objectMetadata = new ObjectMetadata();
        // - 使用输入流存储,需要设置请求长度
        objectMetadata.setContentLength(inputStream.available());
        // - 设置缓存
        objectMetadata.setCacheControl("no-cache");
        // - 设置Content-Type
        objectMetadata.setContentType(fileType);
        //上传文件
        PutObjectResult putResult = cosClient.putObject
                (tencentCOSproperties.getBucketName(), key, inputStream, objectMetadata);
        // 创建文件的网络访问路径
        String url = tencentCOSproperties.getRootSrc() + "/" + key;
        //关闭 cosClient,并释放 HTTP 连接的后台管理线程
        cosClient.shutdown();
        return url;
    }
}

4.编写文件上传控制类

实现思路:
1.依赖注入@Autowired获得腾讯云的工具类
2.遵守Restful开发规范,使用@PostMapping注解声名请求路径
3.使用Result实体类统一响应格式
4.使用@Slf4j注解输出日志到控制台
5.调用工具类upload方法完成文件上传

package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.utils.TencentCOSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RestController
public class UploadController {
    @Autowired
    private TencentCOSUtils tencentCOSUtils;
    //腾讯云存储
    @PostMapping("/upload")
    public Result upload(MultipartFile image) throws Exception {
        log.info("文件上传,文件名:{}",image.getOriginalFilename());
        String url = tencentCOSUtils.upload(image);
        log.info("文件上传完成,文件访问的url为:{}",url);
        return Result.success(url);
    }
}

5.使用postman模拟前端访问请求,验证程序

实现思路:
1.启动idea
2.使用post请求,请求localhost(本机):8080(端口)/upoad(请求路径)
3.选择表单编码格式,提交文件
4.发的请求,得到访问成功的响应

可以查看连接是否为上传的文件,来验证是否上传成功
也可以打开腾讯云查看是否成功上传了文件

在这里插入图片描述

推荐阅读