当前位置: 首页 > news >正文

腾讯云对象存储服务COS

目录

前置操作:

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密钥IDprivate String secretKey; // 腾讯云API密钥Keyprivate 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 {@Autowiredprivate 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 {@Autowiredprivate 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;}@Overridepublic 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);//调用方法获取临时URLString imageUrl = this.getImageUrl(uploadPath);cosUploadVo.setShowUrl(imageUrl);return cosUploadVo;}// 获取临时签名URL@Overridepublic String getImageUrl(String path) {if(!StringUtils.hasText(path)) return "";//获取cosclient对象COSClient cosClient = this.getCosClient();//GeneratePresignedUrlRequestGeneratePresignedUrlRequest 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();
}
http://www.lryc.cn/news/611164.html

相关文章:

  • QtPromise第三方库的介绍和使用
  • 人工智能领域、图欧科技、IMYAI智能助手2025年1月更新月报
  • ubuntu24中部署k8s 1.30.x-底层用docker
  • 相机拍摄的DNG格式照片日期如何修改?你可以用这款工具修改
  • Android异常信号处理详解
  • 【网络运维】Linux:系统启动原理与配置
  • Coze开源了!意味着什么?
  • 在Linux上部署RabbitMQ、Redis、ElasticSearch
  • 无监督学习聚类方法——K-means 聚类及应用
  • NFS CENTOS系统 安装配置
  • 走进“Mesh无线自组网”:开启智能家居和智慧工厂
  • 安科瑞智慧能源管理系统在啤酒厂5MW分布式光伏防逆流控制实践
  • uv与conda环境冲突,无法使用uv环境,安装包之后出现ModuleNotFoundError: No module named ‘xxx‘等解决方法
  • unity之 贴图很暗怎么办
  • 【STM32】HAL库中的实现(四):RTC (实时时钟)
  • python的教务管理系统
  • 江协科技STM32学习笔记1
  • Spring 的依赖注入DI是什么?
  • 【计算机网络】6应用层
  • PostgreSQL——函数
  • 【语音技术】什么是VAD
  • Windows 电脑远程访问,ZeroTier 实现内网穿透完整指南(含原理讲解)
  • NLP自然语言处理 03 Transformer架构
  • 人工智能-python-Sklearn 数据加载与处理实战
  • ChatGPT以及ChatGPT强化学习步骤
  • MLIR Bufferization
  • Linux驱动学习(八)设备树
  • 《手撕设计模式》系列导学目录
  • 防火墙安全策略练习
  • Dot1x认证原理详解