腾讯云COS存储桶服务

This commit is contained in:
syruan 2023-12-03 16:48:30 +08:00
parent 388aaaaada
commit 61e7ea2954
21 changed files with 802 additions and 16 deletions

View File

@ -38,6 +38,12 @@
<groupId>com.bonus.zlpt</groupId>
<artifactId>zlpt-common-swagger</artifactId>
</dependency>
<dependency>
<groupId>com.bonus.zlpt</groupId>
<artifactId>zlpt-home</artifactId>
<version>3.6.3</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>

View File

@ -61,9 +61,13 @@ public class BmCompanyInfoController extends BaseController {
@RequiresPermissions("system:company:edit")
@Log(title = "企业管理", businessType = BusinessType.UPDATE)
@PostMapping("updateCompanyInfo")
public AjaxResult edit(@RequestBody BmCompanyInfo obj) {
Integer deptId = obj.getCompanyId();
return toAjax(bmCompanyInfoService.updateByPrimaryKeySelective(obj));
public AjaxResult updateCompanyInfo(@RequestBody BmCompanyInfo obj) {
try {
Integer companyId = obj.getCompanyId();
return toAjax(bmCompanyInfoService.updateByPrimaryKeySelective(obj));
} catch (Exception e) {
return error(e.getMessage());
}
}
/**
@ -71,9 +75,13 @@ public class BmCompanyInfoController extends BaseController {
*/
@RequiresPermissions("system:company:remove")
@Log(title = "企业管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{deptId}")
public AjaxResult remove(@PathVariable Integer deptId) {
return toAjax(bmCompanyInfoService.deleteByPrimaryKey(deptId));
@PostMapping("/cancelCompany/{id}")
public AjaxResult cancelCompany(@PathVariable Integer id) {
try {
return toAjax(bmCompanyInfoService.deleteByPrimaryKey(id));
} catch (Exception e) {
return error(e.getMessage());
}
}

View File

@ -0,0 +1,154 @@
package com.bonus.zlpt.company.controller;
import com.bonus.zlpt.common.core.domain.MaTypeInfo;
import com.bonus.zlpt.common.core.web.controller.BaseController;
import com.bonus.zlpt.common.core.web.domain.AjaxResult;
import com.bonus.zlpt.common.core.web.page.TableDataInfo;
import com.bonus.zlpt.company.domain.MaUpOff;
import com.bonus.zlpt.company.mapper.MaUpOffMapper;
import com.bonus.zlpt.company.service.impl.MaUpOffServiceImpl;
import com.bonus.zlpt.home.service.MaTypeInfoSevice;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
/**
* 装备上下架管理
(ma_up_off)表控制层
* @author 阮世耀
*/
@RestController
@RequestMapping("/up_off")
public class MaUpOffController extends BaseController {
/**
* 服务对象
*/
@Resource
private MaUpOffServiceImpl maUpOffServiceImpl;
@Resource
private MaUpOffMapper maUpOffMapper;
@Resource
private MaTypeInfoSevice maTypeInfoSevice;
/**
* 获取所有数据
* @param record 筛选条件
*/
@PostMapping("getEquipmentOnShelfReviewList")
public AjaxResult getEquipmentOnShelfReviewList(@RequestBody MaUpOff record) {
try {
return AjaxResult.success(maUpOffMapper.selectAll(record));
} catch (Exception e) {
return AjaxResult.error(e.getMessage());
}
}
/**
* 装备上架审批
* @param record 筛选条件
*/
@PostMapping("checkEquipmentOnShelfInfo")
public AjaxResult checkEquipmentOnShelfInfo(@RequestBody MaUpOff record) {
try {
return AjaxResult.success(maUpOffMapper.updateByPrimaryKeySelective(record));
} catch (Exception e) {
return AjaxResult.error(e.getMessage());
}
}
/**
* 通过id下架装备
*/
@PostMapping("withdrawEquipment")
public AjaxResult withdrawEquipment(@RequestParam Integer equipmentID) {
try {
MaUpOff obj = new MaUpOff();
obj.setId(equipmentID);
obj.setType("2");
return AjaxResult.success(maUpOffMapper.updateByPrimaryKeySelective(obj));
} catch (Exception e) {
return AjaxResult.error(e.getMessage());
}
}
/**
* 批量上架设备
*/
@PostMapping("batchUpOff")
public AjaxResult batchUpOff(@RequestBody List<Integer> ids) {
try {
return AjaxResult.success(maUpOffMapper.batchUpOff(ids));
} catch (Exception e) {
return AjaxResult.error(e.getMessage());
}
}
/**
* 搜索分类
* @return 装备分类列表
*/
@PostMapping("/getEquipmentType")
public TableDataInfo getEquipmentType() {
List<MaTypeInfo> list = maTypeInfoSevice.getMaTypeInfoList();
return getDataTable(list);
}
/**
* 通过主键查询单条数据
*
* @param id 主键
* @return 单条数据
*/
@GetMapping("findEquipmentOnShelfInfo")
public MaUpOff findEquipmentOnShelfInfo(Integer id) {
return maUpOffServiceImpl.selectByPrimaryKey(id);
}
/**
* 导出设备信息
* @param record 筛选条件
* @throws IOException 异常处理
*/
@PostMapping("expEquipmentOnShelfInfo")
public ResponseEntity<byte[]> expEquipmentOnShelfInfo(@RequestBody MaUpOff record) throws IOException {
// 根据条件筛选获取设备信息
List<MaUpOff> devices = maUpOffMapper.selectAll(record);
// 创建一个临时文件用于保存导出的设备信息
Path tempFile = Files.createTempFile("device-export", ".csv");
// 打开临时文件并写入设备信息
try (FileWriter writer = new FileWriter(tempFile.toFile())) {
writer.write("Device ID,Device Name,Device Type\n");
for (MaUpOff device : devices) {
writer.write(device.getId() + "," + device.getMaId() + "," + device.getApplyCompany() + "\n");
}
}
// 将临时文件转换为字节数组并设置响应头
byte[] fileContent = Files.readAllBytes(tempFile);
ResponseEntity<byte[]> response = ResponseEntity.ok()
.header("Content-Disposition", "attachment; filename=device-export.csv")
.header("Content-Type", "text/csv")
.header("Content-Length", String.valueOf(fileContent.length))
.body(fileContent);
// 删除临时文件
Files.deleteIfExists(tempFile);
return response;
}
}

View File

@ -48,8 +48,8 @@ public class MaUserCollectController extends BaseController {
* 获取收藏列表
*/
@RequiresPermissions("system:collect:list")
@GetMapping("/list")
public AjaxResult list(MaUserCollect obj) {
@GetMapping("/getColletList")
public AjaxResult getColletList(MaUserCollect obj) {
try {
List<MaUserCollect> list = maUserCollectMapper.selectAll(obj);
return success(getDataTable(list));
@ -58,6 +58,20 @@ public class MaUserCollectController extends BaseController {
}
}
/**
* 删除 -- 取消收藏
*/
@RequiresPermissions("system:collect:remove")
@Log(title = "取消收藏", businessType = BusinessType.DELETE)
@PostMapping("cancelCollet")
public AjaxResult cancelCollet(@RequestBody MaUserCollect obj) {
try {
return toAjax(maUserCollectService.deleteByPrimaryKey(obj));
} catch (Exception e) {
return error(e.getMessage());
}
}
/**
* 查询 -- 根据设备id获取信息

View File

@ -0,0 +1,60 @@
package com.bonus.zlpt.company.domain;
import java.io.Serializable;
import lombok.Data;
/**
* Description: 设备上下架管理
* @Author 阮世耀
* @Create 2023/12/3 14:38
* @Version 1.0
*/
@Data
public class MaUpOff implements Serializable {
private static final long serialVersionUID = -734284532786259297L;
private Integer id;
/**
* 设备id
*/
private Integer maId;
/**
* 申请时间
*/
private String applyTime;
/**
* 申请人
*/
private String applyUser;
/**
* 申请企业
*/
private String applyCompany;
/**
* 1上架2下架
*/
private String type;
/**
* 审核人
*/
private String auditUser;
/**
* 审核时间
*/
private String auditTime;
/**
* 状态1通过2驳回
*/
private String status;
}

View File

@ -0,0 +1,36 @@
package com.bonus.zlpt.company.mapper;
import com.bonus.zlpt.company.domain.MaUpOff;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* Description: 装备上下架DAO层
* @Author 阮世耀
* @Create 2023/12/3 14:38
* @Version 1.0
*/
@Mapper
public interface MaUpOffMapper {
int deleteByPrimaryKey(Integer id);
int insert(MaUpOff record);
int insertSelective(MaUpOff record);
MaUpOff selectByPrimaryKey(Integer id);
List<MaUpOff> selectAll(MaUpOff record);
/**
* 批量上架装备
*/
int batchUpOff(List<Integer> list);
int updateByPrimaryKeySelective(MaUpOff record);
int updateByPrimaryKey(MaUpOff record);
}

View File

@ -14,7 +14,13 @@ import java.util.List;
@Mapper
public interface MaUserCollectMapper {
int deleteByPrimaryKey(Integer id);
/**
* 根据设备id + 用户id 删除收藏数据
* @param obj 信息
* @return 删除结果
*/
int deleteByPrimaryKey(MaUserCollect obj);
int insert(MaUserCollect record);

View File

@ -0,0 +1,26 @@
package com.bonus.zlpt.company.service;
import com.bonus.zlpt.company.domain.MaUpOff;
/**
* Description:
* @Author 阮世耀
* @Create 2023/12/3 14:38
* @Version 1.0
*/
public interface MaUpOffService{
int deleteByPrimaryKey(Integer id);
int insert(MaUpOff record);
int insertSelective(MaUpOff record);
MaUpOff selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(MaUpOff record);
int updateByPrimaryKey(MaUpOff record);
}

View File

@ -12,7 +12,7 @@ public interface MaUserCollectService{
MaUserCollect selectByMaId(Integer maId);
int deleteByPrimaryKey(Integer id);
int deleteByPrimaryKey(MaUserCollect obj);
int insert(MaUserCollect record);

View File

@ -0,0 +1,51 @@
package com.bonus.zlpt.company.service.impl;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.bonus.zlpt.company.mapper.MaUpOffMapper;
import com.bonus.zlpt.company.domain.MaUpOff;
import com.bonus.zlpt.company.service.MaUpOffService;
/**
* Description:
* @Author 阮世耀
* @Create 2023/12/3 14:38
* @Version 1.0
*/
@Service
public class MaUpOffServiceImpl implements MaUpOffService{
@Resource
private MaUpOffMapper maUpOffMapper;
@Override
public int deleteByPrimaryKey(Integer id) {
return maUpOffMapper.deleteByPrimaryKey(id);
}
@Override
public int insert(MaUpOff record) {
return maUpOffMapper.insert(record);
}
@Override
public int insertSelective(MaUpOff record) {
return maUpOffMapper.insertSelective(record);
}
@Override
public MaUpOff selectByPrimaryKey(Integer id) {
return maUpOffMapper.selectByPrimaryKey(id);
}
@Override
public int updateByPrimaryKeySelective(MaUpOff record) {
return maUpOffMapper.updateByPrimaryKeySelective(record);
}
@Override
public int updateByPrimaryKey(MaUpOff record) {
return maUpOffMapper.updateByPrimaryKey(record);
}
}

View File

@ -28,8 +28,8 @@ public class MaUserCollectServiceImpl implements MaUserCollectService{
}
@Override
public int deleteByPrimaryKey(Integer id) {
return maUserCollectMapper.deleteByPrimaryKey(id);
public int deleteByPrimaryKey(MaUserCollect obj) {
return maUserCollectMapper.deleteByPrimaryKey(obj);
}
@Override

View File

@ -0,0 +1,172 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bonus.zlpt.company.mapper.MaUpOffMapper">
<resultMap id="BaseResultMap" type="com.bonus.zlpt.company.domain.MaUpOff">
<!--@mbg.generated-->
<!--@Table ma_up_off-->
<id column="id" jdbcType="INTEGER" property="id" />
<result column="ma_id" jdbcType="INTEGER" property="maId" />
<result column="apply_time" jdbcType="VARCHAR" property="applyTime" />
<result column="apply_user" jdbcType="VARCHAR" property="applyUser" />
<result column="apply_company" jdbcType="VARCHAR" property="applyCompany" />
<result column="type" jdbcType="VARCHAR" property="type" />
<result column="audit_user" jdbcType="VARCHAR" property="auditUser" />
<result column="audit_time" jdbcType="VARCHAR" property="auditTime" />
<result column="status" jdbcType="VARCHAR" property="status" />
</resultMap>
<sql id="Base_Column_List">
<!--@mbg.generated-->
id, ma_id, apply_time, apply_user, apply_company, `type`, audit_user, audit_time, `status`
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
<!--@mbg.generated-->
select
<include refid="Base_Column_List" />
from ma_up_off
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
<!--@mbg.generated-->
delete from ma_up_off
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" keyColumn="id" keyProperty="id" parameterType="com.bonus.zlpt.company.domain.MaUpOff" useGeneratedKeys="true">
<!--@mbg.generated-->
insert into ma_up_off (ma_id, apply_time, apply_user, apply_company, `type`, audit_user, audit_time, `status`)
values (#{maId,jdbcType=INTEGER}, #{applyTime,jdbcType=VARCHAR}, #{applyUser,jdbcType=VARCHAR},
#{applyCompany,jdbcType=VARCHAR}, #{type,jdbcType=VARCHAR}, #{auditUser,jdbcType=VARCHAR},
#{auditTime,jdbcType=VARCHAR}, #{status,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" keyColumn="id" keyProperty="id" parameterType="com.bonus.zlpt.company.domain.MaUpOff" useGeneratedKeys="true">
<!--@mbg.generated-->
insert into ma_up_off
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="maId != null">
ma_id,
</if>
<if test="applyTime != null and applyTime != ''">
apply_time,
</if>
<if test="applyUser != null and applyUser != ''">
apply_user,
</if>
<if test="applyCompany != null and applyCompany != ''">
apply_company,
</if>
<if test="type != null and type != ''">
`type`,
</if>
<if test="auditUser != null and auditUser != ''">
audit_user,
</if>
<if test="auditTime != null and auditTime != ''">
audit_time,
</if>
<if test="status != null and status != ''">
`status`,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="maId != null">
#{maId,jdbcType=INTEGER},
</if>
<if test="applyTime != null and applyTime != ''">
#{applyTime,jdbcType=VARCHAR},
</if>
<if test="applyUser != null and applyUser != ''">
#{applyUser,jdbcType=VARCHAR},
</if>
<if test="applyCompany != null and applyCompany != ''">
#{applyCompany,jdbcType=VARCHAR},
</if>
<if test="type != null and type != ''">
#{type,jdbcType=VARCHAR},
</if>
<if test="auditUser != null and auditUser != ''">
#{auditUser,jdbcType=VARCHAR},
</if>
<if test="auditTime != null and auditTime != ''">
#{auditTime,jdbcType=VARCHAR},
</if>
<if test="status != null and status != ''">
#{status,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.bonus.zlpt.company.domain.MaUpOff">
<!--@mbg.generated-->
update ma_up_off
<set>
<if test="maId != null">
ma_id = #{maId,jdbcType=INTEGER},
</if>
<if test="applyTime != null and applyTime != ''">
apply_time = #{applyTime,jdbcType=VARCHAR},
</if>
<if test="applyUser != null and applyUser != ''">
apply_user = #{applyUser,jdbcType=VARCHAR},
</if>
<if test="applyCompany != null and applyCompany != ''">
apply_company = #{applyCompany,jdbcType=VARCHAR},
</if>
<if test="type != null and type != ''">
`type` = #{type,jdbcType=VARCHAR},
</if>
<if test="auditUser != null and auditUser != ''">
audit_user = #{auditUser,jdbcType=VARCHAR},
</if>
<if test="auditTime != null and auditTime != ''">
audit_time = #{auditTime,jdbcType=VARCHAR},
</if>
<if test="status != null and status != ''">
`status` = #{status,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.bonus.zlpt.company.domain.MaUpOff">
<!--@mbg.generated-->
update ma_up_off
set ma_id = #{maId,jdbcType=INTEGER},
apply_time = #{applyTime,jdbcType=VARCHAR},
apply_user = #{applyUser,jdbcType=VARCHAR},
apply_company = #{applyCompany,jdbcType=VARCHAR},
`type` = #{type,jdbcType=VARCHAR},
audit_user = #{auditUser,jdbcType=VARCHAR},
audit_time = #{auditTime,jdbcType=VARCHAR},
`status` = #{status,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
</update>
<select id="selectAll" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from ma_up_off
<where>
<if test="id!= null">
id = #{id,jdbcType=INTEGER}
</if>
<if test="maId!= null">
and ma_id = #{maId,jdbcType=INTEGER}
</if>
<if test="applyCompany!= null and applyCompany!= ''">
and apply_company like concat('%',#{applyCompany,jdbcType=VARCHAR},'%')
</if>
</where>
</select>
<select id="batchUpOff" resultType="int">
update ma_up_off set status = '1', type = '1', audit_time = now() where id in
<foreach collection="list" item="item" index="index" open="(" close=")" separator=",">
#{item}
</foreach>
</select>
</mapper>

View File

@ -24,9 +24,8 @@
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
<!--@mbg.generated-->
delete from ma_user_collect
where id = #{id,jdbcType=INTEGER}
where user_id = #{userId,jdbcType=INTEGER} and ma_id = #{maId,jdbcType=INTEGER}
</delete>
<insert id="insert" keyColumn="id" keyProperty="id" parameterType="com.bonus.zlpt.company.domain.MaUserCollect" useGeneratedKeys="true">

View File

@ -39,8 +39,7 @@ public class TypeInfoController extends BaseController
*/
@RequiresPermissions("equip:info:list")
@GetMapping("/list")
public TableDataInfo list(TypeInfo typeInfo)
{
public TableDataInfo list(TypeInfo typeInfo) {
startPage();
List<TypeInfo> list = typeInfoService.selectTypeInfoList(typeInfo);
return getDataTable(list);

View File

@ -16,6 +16,13 @@
</description>
<dependencies>
<!-- 腾讯云cos 存储桶服务 -->
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>5.6.54</version>
</dependency>
<!-- SpringCloud Alibaba Nacos -->
<dependency>

View File

@ -0,0 +1,41 @@
package com.bonus.zlpt.file.config;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* Description: 腾讯云cos配置
*
* @Author 阮世耀
* @Create 2023/12/3 16:26
* @Version 1.0
*/
@Component
public class ConstantPropertiesUtil implements InitializingBean {
@Value("${tencent.cos.file.region}")
private String region;
@Value("${tencent.cos.file.secretid}")
private String secretId;
@Value("${tencent.cos.file.secretkey}")
private String secretKey;
@Value("${tencent.cos.file.bucketname}")
private String bucketName;
public static String END_POINT;
public static String ACCESS_KEY_ID;
public static String ACCESS_KEY_SECRET;
public static String BUCKET_NAME;
@Override
public void afterPropertiesSet() throws Exception {
END_POINT = region;
ACCESS_KEY_ID = secretId;
ACCESS_KEY_SECRET = secretKey;
BUCKET_NAME = bucketName;
}
}

View File

@ -0,0 +1,41 @@
package com.bonus.zlpt.file.controller;
import com.bonus.zlpt.common.core.web.controller.BaseController;
import com.bonus.zlpt.common.core.web.domain.AjaxResult;
import com.bonus.zlpt.file.service.FileUploadTencentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
/**
* Description: 腾讯云文件上传接口
*
* @Author 阮世耀
* @Create 2023/12/3 16:33
* @Version 1.0
*/
@Api(tags = "腾讯云文件上传接口")
@RestController
@RequestMapping("/file/cos")
public class FileUploadTencentController extends BaseController {
@Resource
private FileUploadTencentService fileUploadTencentService;
@ApiOperation(value = "文件上传")
@PostMapping("upload")
public AjaxResult upload(
@ApiParam(name = "file", value = "文件", required = true)
@RequestParam("file") MultipartFile file) {
String uploadUrl = fileUploadTencentService.uploadFile(file);
return success(uploadUrl);
}
}

View File

@ -0,0 +1,20 @@
package com.bonus.zlpt.file.service;
import org.springframework.web.multipart.MultipartFile;
/**
* Description: 腾讯云上传服务
*
* @Author 阮世耀
* @Create 2023/12/3 16:28
* @Version 1.0
*/
public interface FileUploadTencentService {
/**
* 上传文件
* @param file 上传的文件
* @return 上传成功返回文件地址失败返回null
*/
String uploadFile(MultipartFile file);
}

View File

@ -0,0 +1,76 @@
package com.bonus.zlpt.file.service;
import com.bonus.zlpt.common.core.utils.uuid.UUID;
import com.bonus.zlpt.file.config.ConstantPropertiesUtil;
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.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.joda.time.DateTime;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
/**
* Description: 上传接口实现
*
* @Author 阮世耀
* @Create 2023/12/3 16:29
* @Version 1.0
*/
public class FileUploadTencentServiceImpl implements FileUploadTencentService {
/**
* 上传文件到腾讯云对象存储COS
* @param file 要上传的文件
* @return 上传成功返回文件的URL失败返回null
*/
@Override
public String uploadFile(MultipartFile file) {
// 1 初始化用户身份信息secretId, secretKey
String secretId = ConstantPropertiesUtil.ACCESS_KEY_ID;
String secretKey = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 2 设置 bucket 的地域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
Region region = new Region(ConstantPropertiesUtil.END_POINT);
ClientConfig clientConfig = new ClientConfig();
// 这里建议设置使用 https 协议
clientConfig.setHttpProtocol(HttpProtocol.https);
// 3 生成 cos 客户端
COSClient cosClient = new COSClient(cred, clientConfig);
// 存储桶的命名格式为 BucketName-APPID此处填写的存储桶名称必须为此格式
String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
// 对象键(Key)是对象在存储桶中的唯一标识 998u-09iu-09i-333
//在文件名称前面添加uuid值
String key = UUID.randomUUID().toString().replaceAll("-","")
+file.getOriginalFilename();
//对上传文件分组根据当前日期 /2022/11/11
String dateTime = new DateTime().toString("yyyy/MM/dd");
key = dateTime+"/"+key;
try {
//获取上传文件输入流
InputStream inputStream = file.getInputStream();
ObjectMetadata objectMetadata = new ObjectMetadata();
PutObjectRequest putObjectRequest = new PutObjectRequest(
bucketName,
key,
inputStream,
objectMetadata);
// 高级接口会返回一个异步结果Upload
PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
//返回上传文件路径
//https://ggkt-atguigu-1310644373.cos.ap-beijing.myqcloud.com/01.jpg
String url = "https://" + bucketName + "." + "cos" + "." + ConstantPropertiesUtil.END_POINT+".myqcloud.com" + "/" + key;
return url;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

View File

@ -0,0 +1,53 @@
package com.bonus.zlpt.file.utils;
import com.alibaba.fastjson2.JSON;
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.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import java.io.File;
/**
* Description: 腾讯云COS文件上传示例
* @Author 阮世耀
* @Create 2023/12/3 16:23
* @Version 1.0
*/
public class FileUploadTencentCos {
public static void main(String[] args) {
// 1 初始化用户身份信息secretId, secretKey
String secretId = "你的secretId";
String secretKey = "你的secretKey";
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-nanjing");
ClientConfig clientConfig = new ClientConfig(region);
// 这里建议设置使用 https 协议
// 5.6.54 版本开始默认使用了 https
clientConfig.setHttpProtocol(HttpProtocol.https);
// 3 生成 cos 客户端
COSClient cosClient = new COSClient(cred, clientConfig);
try{
// 指定要上传的文件
File localFile = new File("D:\\glkt_work\\glkt\\11.png");
// 指定文件将要存放的存储桶
String bucketName = "你的bucketName";
// 指定文件上传到 COS 上的路径即对象键例如对象键为folder/picture.jpg则表示将文件 picture.jpg 上传到 folder 路径下
String key = "test-11.png";
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
System.out.println(JSON.toJSONString(putObjectResult));
} catch (Exception clientException) {
clientException.printStackTrace();
}
}
}

View File

@ -2,6 +2,23 @@
server:
port: 9300
# 腾讯云cos
tencent:
cos:
file:
# 存储桶所在地域
region: ap-nanjing
# 存储桶所在地域
bucketregion: ap-nanjing
# 存储桶名称
bucketname: zlpt-1259760603
# API账号
secretid: AKIDjJfoiPs9C2e1A5sSoSu77tTq212rTs56
# API密钥
secretkey: rVzLXWM0QceU9bqunTyHNFuMdiaFk4B6
# Spring
spring:
application: