【技术积累】腾讯/阿里云对象存储上传+删除

news/2024/9/19 13:22:08/文章来源:https://www.cnblogs.com/deyo/p/18407485

腾讯/阿里云对象存储上传+删除

  1. 创建储存桶 (后面会用到 储存库名称、访问域名、以及region) region(地域和访问域名)的查询参考: https://cloud.tencent.com/document/product/436/6224
  2. https://www.aliyun.com/product/oss

常用的阿里云、腾讯云

2.创建Api密钥 (后面会用到 secretId、secretKey)

application.yml

qcloud:path: 域名地址bucketName: 储存库名称secretId: 密钥生成的secretIdsecretKey: 密钥生成的secretKeyregion: 地域简称prefix: /images/

工具类:

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.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;import java.io.File;
import java.io.IOException;
import java.util.UUID;/*** @author * @date 2021/6/6 19:31* @role*/
@Data
public class QCloudCosUtils {//API密钥secretIdprivate String secretId;//API密钥secretKeyprivate String secretKey;//存储桶所属地域private String region;//存储桶空间名称private String bucketName;//存储桶访问域名private String path;//上传文件前缀路径(eg:/images/)private String prefix;/*** 上传File类型的文件** @param file* @return 上传文件在存储桶的链接*/public String upload(File file) {//生成唯一文件名String newFileName = generateUniqueName(file.getName());//文件在存储桶中的keyString key = prefix + newFileName;//声明客户端COSClient cosClient = null;try {//初始化用户身份信息(secretId,secretKey)COSCredentials cosCredentials = new BasicCOSCredentials(secretId, secretKey);//设置bucket的区域ClientConfig clientConfig = new ClientConfig(new Region(region));//生成cos客户端cosClient = new COSClient(cosCredentials, clientConfig);//创建存储对象的请求PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);//执行上传并返回结果信息PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);return path + key;} catch (CosClientException e) {e.printStackTrace();} finally {cosClient.shutdown();}return null;}/*** upload()重载方法** @param multipartFile* @return 上传文件在存储桶的链接*/public String upload(MultipartFile multipartFile) {System.out.println(multipartFile);//生成唯一文件名String newFileName = generateUniqueName(multipartFile.getOriginalFilename());//文件在存储桶中的keyString key = prefix + newFileName;//声明客户端COSClient cosClient = null;//准备将MultipartFile类型转为File类型File file = null;try {//生成临时文件file = File.createTempFile("temp", null);//将MultipartFile类型转为File类型multipartFile.transferTo(file);//初始化用户身份信息(secretId,secretKey)COSCredentials cosCredentials = new BasicCOSCredentials(secretId, secretKey);//设置bucket的区域ClientConfig clientConfig = new ClientConfig(new Region(region));//生成cos客户端cosClient = new COSClient(cosCredentials, clientConfig);//创建存储对象的请求PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);//执行上传并返回结果信息PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);return path + key;} catch (IOException e) {e.printStackTrace();} finally {cosClient.shutdown();}return null;}/*** 根据UUID生成唯一文件名** @param originalName* @return*/public String generateUniqueName(String originalName) {return UUID.randomUUID() + originalName.substring(originalName.lastIndexOf("."));}/*** 删除文件*/public boolean deleteFile(String fileName) {String key = prefix + fileName;COSClient cosclient = null;try {//初始化用户身份信息(secretId,secretKey)COSCredentials cosCredentials = new BasicCOSCredentials(secretId, secretKey);//设置bucket的区域ClientConfig clientConfig = new ClientConfig(new Region(region));// 生成cos客户端cosclient = new COSClient(cosCredentials, clientConfig);// 指定要删除的 bucket 和路径cosclient.deleteObject(bucketName, key);// 关闭客户端(关闭后台线程)cosclient.shutdown();}catch (CosClientException e) {e.printStackTrace();}return true;}
}
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import studio.banner.officialwebsite.util.QCloudCosUtils;
/*** 腾讯云对象存储*/
@Configuration
public class QCloudCosUtilsConfig {@ConfigurationProperties(prefix = "qcloud")@Beanpublic QCloudCosUtils qcloudCosUtils() {return new QCloudCosUtils();}
}
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import studio.banner.officialwebsite.entity.RespBean;
import studio.banner.officialwebsite.service.IFileUploadService;/*** @author * @date 2021/6/6 19:42* @role*/
@RestController
@Api(tags = "腾讯云上传接口", value = "TencentPhotoController")
public class TencentPhotoController {protected static final Logger logger = LoggerFactory.getLogger(TencentPhotoController.class);@Autowiredprivate IFileUploadService iFileUploadService;@PostMapping(value = "/upload")@ApiOperation(value = "腾讯云上传接口",notes = "上传图片不能为空",httpMethod = "POST")public RespBean upload(@RequestPart MultipartFile multipartFile) {String url = iFileUploadService.upload(multipartFile);return RespBean.ok("上传成功",url);}@DeleteMapping("delete")@ApiOperation(value = "腾讯云删除接口",httpMethod = "DELETE")@ApiImplicitParam(name = "fileName",value = "图片名",dataTypeClass = String.class)public RespBean delete(@RequestParam String  fileName) {if (iFileUploadService.delete(fileName)){return RespBean.ok("删除成功");}return RespBean.error("删除失败");}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/795228.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

虚拟机安装 gho系统

1.新建 虚拟机2.使用 _优先安装WePE_64_V2.3.exe 制作一个可启动iso3.gho文件 用UltraISO 制作为一个iso文件4.虚拟机用 前面制作的iso文件启动后 分区 ,然后启动 gho工具,再加载iso文件5.此时可以进行克隆还原了

Qt使用绿色pdf阅读器打开文件

1.下载SumatraPDF 2.设置 3.代码void MainWindow::on_pushButton_clicked() {QProcess *process = new QProcess();QString filePath = "C:\\Users\\jude\\Desktop\\su\\11.pdf";QString sumatraPath = "C:\\Users\\jude\\Desktop\\su\\SumatraPDF-3.5.2-64.exe…

基于tf-idf的论文查重

基于tf-idf的论文查重 github地址:https://github.com/gomevie/gomevie/tree/main这个作业属于哪个课程 广工计院计科34班软工这个作业要求在哪里 作业要求 这个作业的目标 设计并实现一个论文查重算法,通过比较原文和抄袭版论文文件,计算并输出重复率。PSP表格PSP2.1 Pers…

Java SE 语法学习

JavaSE 语法 java数据类型基本数据类型整数类型byte 占1个字节,范围:-128-127 short占2个字节,范围:-32768-32767 int占4个字节,范围:-2147483648-2147483647 long占8个字节,范围:-9223372036854775808-9223372036854775807浮点数类型double占8个字节 float占4个字节字…

今天学习和总结

学习了简单的算法知识排序中的快速排序,利用分治的思想来实现快速排序,对于前后大小有问题的进行swap的交换位置,这是基本的模版和源码 include using namespace std; define N 1000100 int A[N]; void quick_sort(int a,int b){ if(a>=b)return ; int i=a-1,j=b+1,x=A[a+b&…

代码整洁之道--读书笔记(7)

代码整洁之道简介: 本书是编程大师“Bob 大叔”40余年编程生涯的心得体会的总结,讲解要成为真正专业的程序员需要具备什么样的态度,需要遵循什么样的原则,需要采取什么样的行动。作者以自己以及身边的同事走过的弯路、犯过的错误为例,意在为后来者引路,助其职业生涯迈上更…

痞子衡嵌入式:在MDK开发环境下自定义安装与切换不同编译器版本的方法

大家好,我是痞子衡,是正经搞技术的痞子。今天痞子衡给大家分享的是在MDK开发环境下自定义安装与切换不同编译器版本的方法。Keil MDK 想必是嵌入式开发者最熟悉的工具之一了,自 2005 年 Arm 公司收购 Keil 公司之后,MDK 就走上了发展快车道,从 v2.50a 一路狂奔到现在最新的…

思源笔记-S3-七牛云-多设备同步

文档参考:思源笔记配置 S3 同步、思源笔记使用七牛云 编写日期:2024.9.9一、思源笔记安装思源笔记官方下载地址选择对应系统版本进行下载双击【SiYuan Installer.exe】进行安装二、注册账号注册账号是为了购买订阅,订阅后才提供 S3/WEBDAV 同步功能打开 SiYuan点击左上角-「…

JMeter性能测试快速入门

1.安装Jmeter Jmeter依赖于JDK,所以必须确保当前计算机上已经安装了JDK,并且配置了环境变量。 1.1.下载 可以Apache Jmeter官网下载,地址:http://jmeter.apache.org/download_jmeter.cgi 1.2.解压 因为下载的是zip包,解压缩即可使用,目录结构如下:其中的bin目录就是执行…

基于Axis 1.4的Web Service入门

最近有个客户使用的是Axis 1.4创建的Web Service,很久没用了,所以整理下这块的知识。 基于JDK 1.8和Eclipse Mars开发一个简单的Hello world Web Service public interface HelloService {String hello(String name);} public class HelloServiceImpl implements HelloServic…

第四周作业

1、安装burp并实现抓取HTTP站点的数据包(HTTPS站点暂时不要求) 下方练习已完成 2、练习Tomcat PUT方法任意写文件漏洞(CVE-2017-12615),提供蚁剑连接成功截图 # 搜索镜像 docker search cve-2017-12615 # 拉取镜像 docker pull cved/cve-2017-12615 # 查看该镜像的详细信息…