SpringBoot学习——腾讯云文件上传+删除

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

在这里插入图片描述

创建储存桶
在这里插入图片描述

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

在这里插入图片描述

application.yml

qcloud:
  path: 域名地址
  bucketName: 储存库名称
  secretId: 密钥生成的secretId
  secretKey: 密钥生成的secretKey
  region: 地域简称
  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密钥secretId
    private String secretId;
    //API密钥secretKey
    private 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());
        //文件在存储桶中的key
        String 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());
        //文件在存储桶中的key
        String 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;
    }
}

QCloudCosUtilsConfig.java


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")
    @Bean
    public QCloudCosUtils qcloudCosUtils() {
        return new QCloudCosUtils();
    }
}

controller 测试

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);
    @Autowired
    private 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("删除失败");

    }

}
可以使用腾讯云官方提供的Java SDK,具体步骤如下: 1. 在pom.xml文件中引入腾讯云cos-java-sdk-v5依赖: ```xml <dependency> <groupId>com.qcloud</groupId> <artifactId>cos_api</artifactId> <version>5.6.19</version> </dependency> ``` 2. 创建腾讯云cos的配置类: ```java @Configuration public class TencentCosConfig { @Value("${tencent.cos.secretId}") private String secretId; @Value("${tencent.cos.secretKey}") private String secretKey; @Value("${tencent.cos.region}") private String region; @Value("${tencent.cos.bucketName}") private String bucketName; @Bean public COSCredentials cosCredentials() { return new BasicCOSCredentials(secretId, secretKey); } @Bean public ClientConfig clientConfig() { ClientConfig clientConfig = new ClientConfig(); clientConfig.setRegion(new Region(region)); return clientConfig; } @Bean public COSClient cosClient() { return new COSClient(cosCredentials(), clientConfig()); } @Bean public String bucketName() { return bucketName; } } ``` 其中,secretId和secretKey是腾讯云提供的访问密钥,region是存储桶所在的地域,bucketName是存储桶的名称。可以在配置文件中配置这些变量,这里用@Value注解获取。 3. 在上传文件的Controller中注入cosClient和bucketName,实现文件上传方法: ```java @RestController public class FileController { @Autowired private COSClient cosClient; @Autowired private String bucketName; @PostMapping("/uploadFile") public String uploadFile(@RequestParam("file") MultipartFile file) throws Exception { ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentLength(file.getSize()); objectMetadata.setContentType(file.getContentType()); String fileName = UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(file.getOriginalFilename()); PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, file.getInputStream(), objectMetadata); cosClient.putObject(putObjectRequest); return "https://" + bucketName + ".cos." + "region" + ".myqcloud.com/" + fileName; } } ``` 这里上传文件的方式为MultipartFile类型,使用Apache Commons IO工具类获取文件后缀名,并用UUID生成随机文件名。然后创建PutObjectRequest对象,调用cosClient的putObject方法上传文件,最后将文件URL返回给前端。 希望以上信息能对你有所帮助。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值