腾讯云对象存储服务COS

发布于:2025-08-06 ⋅ 阅读:(12) ⋅ 点赞:(0)

目录

前置操作:

service-driver远程上传文件:

司机端web接口:


前置操作:

首先进入腾讯云官网:AI驱动 智领未来_腾讯云https://cloud.tencent.com/act/pro/warmup202506?fromSource=gwzcw.9884755.9884755.9884755&utm_medium=cpc&utm_id=gwzcw.9884755.9884755.9884755&msclkid=332664077e8117a4b4900c96dd1fe741#LH

  • 项目基于腾讯云对象存储服务COS,存储认证相关资料(身份证、驾驶证等保密信息)

  • 要使用腾讯云对象存储服务,首先进行开通,注册腾讯云之后,开通就可以了

  • 使用对象存储服务,可以在控制台里面进行操作,也可以使用Java代码进行操作,这些操作,腾讯云官方提供详细文档说明,按照文档就方便进行操作

下面是官方文档:Java版 对象存储 快速入门_腾讯云https://cloud.tencent.com/document/product/436/10199

 步骤详情:

首先引入依赖:

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

 之后在配置文件配置相关信息:

tencent:
  cloud:
    secretId: **************************
    secretKey: *****************************
    region: ap-beijing         # 根据自己的地区选择
    bucketPrivate: daijia-private-1307503602  # 根据自己的bucket名称选择

随后创建配置类:

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

@Data
@Component
@ConfigurationProperties(prefix = "tencent.cloud")
public class TencentCloudProperties {

    private String secretId;  // 腾讯云API密钥ID
    private String secretKey; // 腾讯云API密钥Key
    private String region;    // 存储桶地域(可选值:ap-beijing(北京)、ap-shanghai(上海)等)
    private String bucketPrivate;  // 私有存储桶名称
}

service-driver远程上传文件:

 在service-driver中定义一个远程上传接口:

@Slf4j
@Tag(name = "腾讯云cos上传接口管理")
@RestController
@RequestMapping(value="/cos")
@SuppressWarnings({"unchecked", "rawtypes"})
public class CosController {

    @Autowired
    private CosService cosService;
    
    @Operation(summary = "上传")
    @PostMapping("/upload")
    public Result<CosUploadVo> upload(@RequestPart("file") MultipartFile file, 
                                      @RequestParam("path") String path) {
        CosUploadVo cosUploadVo = cosService.upload(file,path);
        return Result.ok(cosUploadVo);
    }

}

 在Service中:

步骤详情:

  1. 初始化用户的身份信息,并设置bucket的地域与COS地域。
  2. 设置文件元数据信息(大小,编码格式,内容类型)。
  3. 向bucket保存文件(可修改uploadPath,当前路径为"/driver/auth/0o98754.jpg"),随后调用cosClient.putObject()上传文件后,cosClient.shutdown()关闭。【cosClient为自定义的远程调用方法(封装上传文件)】
  4. 若想要让其上传文件地址临时有效,则需获取临时签名URL:
    (1)获取cosClient对象,定义请求的HTTP方法(下载GET,删除DELETE),通过cosClient.generatePresignedUrl()方法获取一个临时的URL。
    (2)将该URL设置并返回。
@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CosServiceImpl implements CosService {

    @Autowired
    private TencentCloudProperties tencentCloudProperties;

    // 创建私有存储桶的COS客户端
    private COSClient getPrivateCOSClient() {
        COSCredentials cred = new BasicCOSCredentials(tencentCloudProperties.getSecretId(), tencentCloudProperties.getSecretKey());
        // 设置 bucket 的地域, COS 地域
        Region region = new Region(tencentCloudProperties.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        // 这里建议设置使用 https 协议
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }
    @Override
    public CosUploadVo upload(MultipartFile file, String path) {
        // 调用上面创建私有存储桶的COS客户端的方法
        COSClient cosClient = this.getPrivateCOSClient();

        //文件上传
        //元数据信息
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentLength(file.getSize());
        meta.setContentEncoding("UTF-8");
        meta.setContentType(file.getContentType());

        //向存储桶中保存文件
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); //文件后缀名
        String uploadPath = "/driver/" + path + "/" + UUID.randomUUID().toString().replaceAll("-", "") + fileType;
        // 假设传输文件为01.jpg
        // 在腾讯云的路径就是"/driver/auth/0o98754.jpg"
        PutObjectRequest putObjectRequest = null;
        try {
            // bucket名称+文件传输路径+文件输入流+元数据对象
            putObjectRequest = new PutObjectRequest(tencentCloudProperties.getBucketPrivate(),
                    uploadPath,
                    file.getInputStream(),
                    meta);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 标准存储
        putObjectRequest.setStorageClass(StorageClass.Standard);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest); // ​腾讯云COS官方SDK上传文件
        cosClient.shutdown();

        //业务逻辑:
        //返回vo对象
        CosUploadVo cosUploadVo = new CosUploadVo();
        cosUploadVo.setUrl(uploadPath);
        //调用方法获取临时URL
        String imageUrl = this.getImageUrl(uploadPath);
        cosUploadVo.setShowUrl(imageUrl);
        return cosUploadVo;
    }

    // 获取临时签名URL
    @Override
    public String getImageUrl(String path) {
        if(!StringUtils.hasText(path)) return "";
        //获取cosclient对象
        COSClient cosClient = this.getCosClient();
        //GeneratePresignedUrlRequest
        GeneratePresignedUrlRequest request =
                new GeneratePresignedUrlRequest(tencentCloudProperties.getBucketPrivate(),
                path, HttpMethodName.GET);
        //设置临时URL有效期为15分钟
        Date date = new DateTime().plusMinutes(15).toDate();
        request.setExpiration(date);
        //调用方法获取
        URL url = cosClient.generatePresignedUrl(request);
        cosClient.shutdown();
        return url.toString();
    }
}

feign接口:

/**
 * 上传
 * @param file
 * @param path
 * @return
 */
@PostMapping(value = "/cos/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
Result<CosUploadVo> upload(@RequestPart("file") MultipartFile file, @RequestParam("path") String path);

司机端web接口:

首先编写Controller:

@Autowired
private CosService cosService;

@Operation(summary = "上传")
@GuiguLogin
@PostMapping("/upload")
public Result<CosUploadVo> upload(@RequestPart("file") MultipartFile file, @RequestParam(name = "path", defaultValue = "auth") String path) {
   return Result.ok(cosService.upload(file, path));
}

之后进行远程调用上传接口:

@Override
public CosUploadVo upload(MultipartFile file, String path) {
    return cosFeignClient.upload(file, path).getData();
}

网站公告

今日签到

点亮在社区的每一天
去签到