ToB企服应用市场:ToB评测及商务社交产业平台

标题: 【技术积累】腾讯/阿里云对象存储上传+删除 [打印本页]

作者: 天津储鑫盛钢材现货供应商    时间: 2024-9-10 22:39
标题: 【技术积累】腾讯/阿里云对象存储上传+删除
腾讯/阿里云对象存储上传+删除

常用的阿里云、腾讯云

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

application.yml
  1. qcloud:
  2.   path: 域名地址
  3.   bucketName: 储存库名称
  4.   secretId: 密钥生成的secretId
  5.   secretKey: 密钥生成的secretKey
  6.   region: 地域简称
  7.   prefix: /images/
复制代码
工具类:
  1. import com.qcloud.cos.COSClient;
  2. import com.qcloud.cos.ClientConfig;
  3. import com.qcloud.cos.auth.BasicCOSCredentials;
  4. import com.qcloud.cos.auth.COSCredentials;
  5. import com.qcloud.cos.exception.CosClientException;
  6. import com.qcloud.cos.exception.CosServiceException;
  7. import com.qcloud.cos.model.PutObjectRequest;
  8. import com.qcloud.cos.model.PutObjectResult;
  9. import com.qcloud.cos.region.Region;
  10. import lombok.Data;
  11. import org.springframework.web.multipart.MultipartFile;
  12. import java.io.File;
  13. import java.io.IOException;
  14. import java.util.UUID;
  15. /**
  16. * @author
  17. * @date 2021/6/6 19:31
  18. * @role
  19. */
  20. @Data
  21. public class QCloudCosUtils {
  22.     //API密钥secretId
  23.     private String secretId;
  24.     //API密钥secretKey
  25.     private String secretKey;
  26.     //存储桶所属地域
  27.     private String region;
  28.     //存储桶空间名称
  29.     private String bucketName;
  30.     //存储桶访问域名
  31.     private String path;
  32.     //上传文件前缀路径(eg:/images/)
  33.     private String prefix;
  34.     /**
  35.      * 上传File类型的文件
  36.      *
  37.      * @param file
  38.      * @return 上传文件在存储桶的链接
  39.      */
  40.     public String upload(File file) {
  41.         //生成唯一文件名
  42.         String newFileName = generateUniqueName(file.getName());
  43.         //文件在存储桶中的key
  44.         String key = prefix + newFileName;
  45.         //声明客户端
  46.         COSClient cosClient = null;
  47.         try {
  48.             //初始化用户身份信息(secretId,secretKey)
  49.             COSCredentials cosCredentials = new BasicCOSCredentials(secretId, secretKey);
  50.             //设置bucket的区域
  51.             ClientConfig clientConfig = new ClientConfig(new Region(region));
  52.             //生成cos客户端
  53.             cosClient = new COSClient(cosCredentials, clientConfig);
  54.             //创建存储对象的请求
  55.             PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
  56.             //执行上传并返回结果信息
  57.             PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
  58.             return path + key;
  59.         } catch (CosClientException e) {
  60.             e.printStackTrace();
  61.         } finally {
  62.             cosClient.shutdown();
  63.         }
  64.         return null;
  65.     }
  66.     /**
  67.      * upload()重载方法
  68.      *
  69.      * @param multipartFile
  70.      * @return 上传文件在存储桶的链接
  71.      */
  72.     public String upload(MultipartFile multipartFile) {
  73.         System.out.println(multipartFile);
  74.         //生成唯一文件名
  75.         String newFileName = generateUniqueName(multipartFile.getOriginalFilename());
  76.         //文件在存储桶中的key
  77.         String key = prefix + newFileName;
  78.         //声明客户端
  79.         COSClient cosClient = null;
  80.         //准备将MultipartFile类型转为File类型
  81.         File file = null;
  82.         try {
  83.             //生成临时文件
  84.             file = File.createTempFile("temp", null);
  85.             //将MultipartFile类型转为File类型
  86.             multipartFile.transferTo(file);
  87.             //初始化用户身份信息(secretId,secretKey)
  88.             COSCredentials cosCredentials = new BasicCOSCredentials(secretId, secretKey);
  89.             //设置bucket的区域
  90.             ClientConfig clientConfig = new ClientConfig(new Region(region));
  91.             //生成cos客户端
  92.             cosClient = new COSClient(cosCredentials, clientConfig);
  93.             //创建存储对象的请求
  94.             PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
  95.             //执行上传并返回结果信息
  96.             PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
  97.             return path + key;
  98.         } catch (IOException e) {
  99.             e.printStackTrace();
  100.         } finally {
  101.             cosClient.shutdown();
  102.         }
  103.         return null;
  104.     }
  105.     /**
  106.      * 根据UUID生成唯一文件名
  107.      *
  108.      * @param originalName
  109.      * @return
  110.      */
  111.     public String generateUniqueName(String originalName) {
  112.         return UUID.randomUUID() + originalName.substring(originalName.lastIndexOf("."));
  113.     }
  114.     /**
  115.      * 删除文件
  116.      */
  117.     public boolean deleteFile(String fileName) {
  118.         String key = prefix + fileName;
  119.         COSClient cosclient = null;
  120.         try {
  121.             //初始化用户身份信息(secretId,secretKey)
  122.             COSCredentials cosCredentials = new BasicCOSCredentials(secretId, secretKey);
  123.             //设置bucket的区域
  124.             ClientConfig clientConfig = new ClientConfig(new Region(region));
  125.             // 生成cos客户端
  126.             cosclient = new COSClient(cosCredentials, clientConfig);
  127.             // 指定要删除的 bucket 和路径
  128.             cosclient.deleteObject(bucketName, key);
  129.             // 关闭客户端(关闭后台线程)
  130.             cosclient.shutdown();
  131.         }catch (CosClientException e) {
  132.             e.printStackTrace();
  133.         }
  134.         return true;
  135.     }
  136. }
复制代码
  1. import org.springframework.boot.context.properties.ConfigurationProperties;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import studio.banner.officialwebsite.util.QCloudCosUtils;
  5. /**
  6. * 腾讯云对象存储
  7. */
  8. @Configuration
  9. public class QCloudCosUtilsConfig {
  10.     @ConfigurationProperties(prefix = "qcloud")
  11.     @Bean
  12.     public QCloudCosUtils qcloudCosUtils() {
  13.         return new QCloudCosUtils();
  14.     }
  15. }
复制代码
  1. import io.swagger.annotations.Api;
  2. import io.swagger.annotations.ApiImplicitParam;
  3. import io.swagger.annotations.ApiOperation;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.web.bind.annotation.*;
  8. import org.springframework.web.multipart.MultipartFile;
  9. import studio.banner.officialwebsite.entity.RespBean;
  10. import studio.banner.officialwebsite.service.IFileUploadService;
  11. /**
  12. * @author
  13. * @date 2021/6/6 19:42
  14. * @role
  15. */
  16. @RestController
  17. @Api(tags = "腾讯云上传接口", value = "TencentPhotoController")
  18. public class TencentPhotoController {
  19.     protected static final Logger logger = LoggerFactory.getLogger(TencentPhotoController.class);
  20.     @Autowired
  21.     private IFileUploadService iFileUploadService;
  22.     @PostMapping(value = "/upload")
  23.     @ApiOperation(value = "腾讯云上传接口",notes = "上传图片不能为空",httpMethod = "POST")
  24.     public RespBean upload(@RequestPart MultipartFile multipartFile) {
  25.         String url = iFileUploadService.upload(multipartFile);
  26.         return RespBean.ok("上传成功",url);
  27.     }
  28.     @DeleteMapping("delete")
  29.     @ApiOperation(value = "腾讯云删除接口",httpMethod = "DELETE")
  30.     @ApiImplicitParam(name = "fileName",value = "图片名",dataTypeClass = String.class)
  31.     public RespBean delete(@RequestParam String  fileName) {
  32.         if (iFileUploadService.delete(fileName)){
  33.             return RespBean.ok("删除成功");
  34.         }
  35.         return RespBean.error("删除失败");
  36.     }
  37. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4