河南循中网络科技有限公司 - 精心创作,详细分解,按照步骤,均可成功!


文章目录

  • 学习资料
  • 集成腾讯云COS存储
    • 添加pom依赖
    • common的pom文件
    • yaml配置
    • 创建TencentCosUtil工具类
    • 创建TencentCosController类
    • 测试结果

学习资料

腾讯云COS存储API文档

集成腾讯云COS存储

添加pom依赖

     <!-- 腾讯云cos存储 --><cos_api.version>5.6.89</cos_api.version><!-- alibaba JSON --><fastjson.version>2.0.11</fastjson.version><!-- apache公共基础类 --><commons-lang3.version>3.12.0</commons-lang3.version>
     <!-- 腾讯云cos存储 --><dependency><groupId>com.qcloud</groupId><artifactId>cos_api</artifactId><version>${cos_api.version}</version></dependency><!-- alibaba JSON --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>${fastjson.version}</version></dependency><!-- apache公共基础类 --><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>${commons-lang3.version}</version></dependency>

common的pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.xz</groupId><artifactId>common</artifactId><version>0.0.1-SNAPSHOT</version><name>common</name><description>河南循中网络科技有限公司 - 通用工具</description><!-- 子模块打包类型必须为jar --><packaging>jar</packaging><!-- parent指明继承关系,给出被继承的父项目的具体信息 --><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.1</version><relativePath/> <!-- lookup parent from repository --></parent><!-- 版本控制 --><properties><java.version>1.8</java.version><!-- 实体类注解 --><lombok.version>1.18.24</lombok.version><!-- swagger --><springfox-boot-starter.version>3.0.0</springfox-boot-starter.version><!-- 腾讯云cos存储 --><cos_api.version>5.6.89</cos_api.version><!-- alibaba JSON --><fastjson.version>2.0.11</fastjson.version><!-- apache公共基础类 --><commons-lang3.version>3.12.0</commons-lang3.version></properties><!-- 引入的jar包 --><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- 实体类注解 --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>${lombok.version}</version></dependency><!-- swagger --><dependency><groupId>io.springfox</groupId><artifactId>springfox-boot-starter</artifactId><version>${springfox-boot-starter.version}</version></dependency><!-- spring boot内置redis --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><!-- 腾讯云cos存储 --><dependency><groupId>com.qcloud</groupId><artifactId>cos_api</artifactId><version>${cos_api.version}</version></dependency><!-- alibaba JSON --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>${fastjson.version}</version></dependency><!-- apache公共基础类 --><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>${commons-lang3.version}</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

yaml配置

#腾讯云COS存储
tencentCosUtil:secretId: 开发者拥有的项目身份识别 ID,用于身份认证,可在 API 密钥管理 页面获取secretKey: 开发者拥有的项目身份密钥,可在 API 密钥管理 页面获取bucketName: 存储桶名称格式,用户在使用 API、SDK 时,需要按照此格式填写存储桶名称。例如 examplebucket-1250000000,含义为该存储桶 examplebucket 归属于 APPID 为1250000000的用户accessUrl: 存储桶配置管理中访问域名的URL

创建TencentCosUtil工具类

由于上传文件时form-data更节省流量,而base64的原始是3字节转换成4字节,也就是把24bit转换成4个6bit,然后6bit再自己补位,最后占据的是32bit,所以原来的体积是base64体积的3/4,故而放弃base64上传文件,只使用form-data方式上传。

package com.xz.cos;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.PutObjectRequest;
import com.qcloud.cos.region.Region;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.ServletContext;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;/*** 腾讯COS存储*/
@Component
public class TencentCosUtil {private static String secretId;private static String secretKey;private static String bucketName;private static String accessUrl;@Value("${tencentCosUtil.secretId}")public void setSecretId(String secretId){this.secretId = secretId;}@Value("${tencentCosUtil.secretKey}")public void setSecretKey(String secretKey){this.secretKey = secretKey;}@Value("${tencentCosUtil.bucketName}")public void setBucketName(String bucketName){this.bucketName = bucketName;}@Value("${tencentCosUtil.accessUrl}")public void setAccessUrl(String accessUrl){this.accessUrl = accessUrl;}/*** 上传文件* @param fileMul* @param cosPath COS上传路径,示例:/upload/file/* @param context* @throws Exception* @return*/public static String uploadFile(MultipartFile fileMul, String cosPath,ServletContext context) throws Exception{//临时文件路径String temporaryFile = context.getRealPath("/") +"/upload"+"/temporaryFile";//效验临时文件是否存在File localFile = new File(temporaryFile);if (!localFile.exists()) {//临时文件不存在,创造临时文件localFile.mkdirs();}//创造临时文件名称String fileName = fileMul.getOriginalFilename();String name = "/" + RandomStringUtils.randomNumeric(6)+System.currentTimeMillis()+System.nanoTime()+RandomStringUtils.randomNumeric(6)+fileName.substring(fileName.lastIndexOf('.'));//创造临时文件图片temporaryFile = temporaryFile+name;FileOutputStream fos;fos = new FileOutputStream(temporaryFile);fos.write(fileMul.getBytes());fos.flush();fos.close();// 使用COSFile file = new File(temporaryFile);// 1 初始化用户身份信息(secretId, secretKey)。// SECRETID和SECRETKEY请登录访问管理控制台 https://console.cloud.tencent.com/cam/capi 进行查看和管理COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);// 2 设置 bucket 的地域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224// clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。Region region = new Region("ap-shanghai");ClientConfig clientConfig = new ClientConfig(region);// 这里建议设置使用 https 协议// 从 5.6.54 版本开始,默认使用了 httpsclientConfig.setHttpProtocol(HttpProtocol.https);// 3 生成 cos 客户端。COSClient cosClient = new COSClient(cred, clientConfig);//格式化时间SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, cosPath+sdf.format(new Date())+name, file);cosClient.putObject(putObjectRequest);String saveUrl = accessUrl+putObjectRequest.getKey();// 删除用户上传临时文件File localImgFile = new File(temporaryFile);localImgFile.delete();return saveUrl;}
}

创建TencentCosController类

package com.xz.controller;import com.alibaba.fastjson.JSONObject;
import com.xz.cos.TencentCosUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;@Api(tags = "腾讯云COS存储")
@RestController
public class TencentCosController {private Logger logger = LoggerFactory.getLogger(this.getClass());@Resourceprivate TencentCosUtil tencentCosUtil;@ApiOperation(value = "上传文件,form-data方式,传值file",notes = "上传文件,form-data方式,传值file")@PostMapping(value = "/uploadFile")public JSONObject uploadFile(HttpServletRequest req, HttpServletResponse res) {JSONObject data = new JSONObject();try{MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) req;MultipartFile file = mreq.getFile("file");if (file.getSize() > 0) {String path = "/upload/file/";String fileUrl = tencentCosUtil.uploadFile(file, path, req.getServletContext());data.put("code",200);data.put("fileUrl",fileUrl);return data;}else{data.put("code",400);data.put("msg","请上传文件");return data;}}catch (Exception e){e.printStackTrace();logger.error(e.getMessage());data.put("code",500);data.put("msg","网络开小差了...");return data;}}
}

测试结果

SpringBoot集成腾讯云COS存储相关推荐

  1. SpringBoot集成腾讯云存储COS服务

    前言 该文章会先简单的介绍一下腾讯云的COS存储,然后演示如何在SpringBoot项目中集成COS,每一步都有记录,保证初学者也能看懂. 文章目录 前言 1.腾讯云对象存储介绍 1.1.开通&quo ...

  2. SpringBoot整合腾讯云COS对象存储实现文件上传

    企业级项目开发中都会有文件.图片.视频等文件上传并能够访问的场景,对于初学者Demo可能会直接存储在应用服务器上:对于传统项目可能会单独搭建FastDFS.MinIO等文件服务来实现存储,这种方案可能 ...

  3. springboot整合腾讯云cos对象储存

    一:腾讯云前期准备 直接在腾讯云中搜索"对象存储",立即使用 点击存储桶列表,创建存储桶 填写基本信息:所属地域,名称,访问权限(公有读写) 下一步,下一步,创建,存储桶创建成功 ...

  4. 使用springboot集成腾讯云短信服务,解决配置文件读取乱码问题

    使用springboot集成腾讯云短信服务,解决配置文件读取乱码问题 参考文章: (1)使用springboot集成腾讯云短信服务,解决配置文件读取乱码问题 (2)https://www.cnblog ...

  5. SpringBoot集成腾讯云对象储存

    第一步:添加pom.xml文件 <!-- 腾讯云cos存储 --> <dependency><groupId>com.qcloud</groupId>& ...

  6. 阿里巴巴 OSS与AWS(亚马逊) S3 和腾讯云cos 存储服务 介绍篇

    前言 对象存储服务,简单来说,可以把它当成一个"网盘",可以上传下载数据,也可以直接在这个"网盘"中对文件进行某些操作. 1.定时或者基于某种条件自动地,每天从 ...

  7. 腾讯云COS存储是什么_腾讯云COS有什么用?

    由于这是给新手写的东西,就尽量整得简单易懂些吧. 作为国内第二大的云服务厂商,安全性,可靠性这些东西就不用过多做介绍了(这里并非说他绝对安全,而是比那些小平台的安全性高N个级别) 什么是腾讯云COS? ...

  8. SpringBoot整合腾讯云COS(上传)

    腾讯云COS文档:对象存储 快速入门-SDK 文档-文档中心-腾讯云 (tencent.com) 开通腾讯云COS 创建存储桶 请求域名可做拼接文件访问URL使用 然后下一步即可 上传文件时需要以上红 ...

  9. springboot使用腾讯云对象存储

    原以为对象存储很难 毕竟之前我用了下 发现完全不会 今天静下心来研究了下 发现其实挺简单的 直接搜索 点击这个 这个秘钥很重要 需要保存好 点击配置 加上这三个 一共是五个数据 我们都是要用到的 导入 ...

最新文章

  1. Objective-C中的block块语法
  2. JUNOS LDP标签分发过程详解
  3. KALI Linux 系统安装 翻译
  4. 负样本的艺术,再读Facebook双塔向量召回算法
  5. Invalid argument: Key: label. Data types don't match. Data type: int64 but expected type: float
  6. OneNote使用技巧及运用
  7. VS2008下编译C++程序,找不到 stdint.h,原因及解决方案
  8. 多学一点(十二)——使用extundelete恢复Linux下误删除文件
  9. 【转】 Android定时器
  10. UEFI开发探索31–鼠标GUI构建
  11. 《DOOM启世录(纪念版) 》此书出了纪念版,好像内容没变
  12. 指尖上的学问——wi输入法开发实记
  13. Halcon软件和license下载
  14. 涡CFTurbo 10.2.6 2017泵轮涡旋式机械设计
  15. zabbix—监控mysql数据
  16. 甲骨文裁员是在为云业务转型太慢埋单吗?
  17. 苹果官方mfi认证名单_苹果入驻抖音,完成官方认证
  18. 怎么在小程序里开店铺?【小程序开店】
  19. 用c语言写出一个金字塔
  20. 【报告分享】小红书平台2021 11.11期间行业投放分析报告-千瓜数据(附下载)

热门文章

  1. xp系统rps服务器不可用,电脑xp系统的已经连接上了wifi却上不了 – 手机爱问
  2. python语法错误怎么帮助排痰_智慧职教APPPython程序设计基础作业答案
  3. PingCAP 入选 2022 Gartner 云数据库“客户之声”,获评“卓越表现者”最高分
  4. android Region类介绍
  5. 【书中自有黄金屋】《重构-改善既有代码的设计》读书笔记
  6. STM32F407霸天虎HAL库CubeMX学习笔记——DS18B20
  7. C语言课程设计之学生学籍管理系统
  8. supervisor使用方法
  9. 浅谈路由器的wan、lan、wlan口和vlan/trunk口
  10. 当ellipsis遇到flex布局