腾讯云COS上传下载文件

1、初始化COSClient


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.region.Region;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.Serializable;

/**
 * 云存储配置信息
 */
@Configuration
@Component
public class CloudStorageConfig implements Serializable {
    private static final long serialVersionUID = 1L;

    //腾讯云绑定的域名
    @NotBlank(message = "腾讯云绑定的域名不能为空")
    @URL(message = "腾讯云绑定的域名格式不正确")
    private String qcloudDomain;
    //腾讯云路径前缀
    private String qcloudPrefix;
    //腾讯云AppId
    @NotNull(message = "腾讯云AppId不能为空")
    private Integer qcloudAppId;
    //腾讯云SecretId
    @NotBlank(message = "腾讯云SecretId不能为空")
    @Value("${app.cos.secretId}")
    private String qcloudSecretId;
    //腾讯云SecretKey
    @NotBlank(message = "腾讯云SecretKey不能为空")
    @Value("${app.cos.secretKey}")
    private String qcloudSecretKey;
    //腾讯云BucketName
    @NotBlank(message = "腾讯云BucketName不能为空")
    @Value("${app.cos.bucketName}")
    private String qcloudBucketName;
    //腾讯云COS所属地区
    @NotBlank(message = "所属地区不能为空")
    @Value("${app.cos.regionName}")
    private String qcloudRegion;

    @Bean
    public COSClient getCOSClient() {
        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(qcloudSecretId, qcloudSecretKey);
        // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        // clientConfig中包含了设置region, https(默认http), 超时, 代理等set方法, 使用可参见源码或者接口文档FAQ中说明
        ClientConfig clientConfig = new ClientConfig(new Region(qcloudRegion));
        // 3 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        return cosclient;
    }

    public String getQcloudDomain() {
        return qcloudDomain;
    }

    public void setQcloudDomain(String qcloudDomain) {
        this.qcloudDomain = qcloudDomain;
    }

    public String getQcloudPrefix() {
        return qcloudPrefix;
    }

    public void setQcloudPrefix(String qcloudPrefix) {
        this.qcloudPrefix = qcloudPrefix;
    }

    public Integer getQcloudAppId() {
        return qcloudAppId;
    }

    public void setQcloudAppId(Integer qcloudAppId) {
        this.qcloudAppId = qcloudAppId;
    }

    public String getQcloudSecretId() {
        return qcloudSecretId;
    }

    public void setQcloudSecretId(String qcloudSecretId) {
        this.qcloudSecretId = qcloudSecretId;
    }

    public String getQcloudSecretKey() {
        return qcloudSecretKey;
    }

    public void setQcloudSecretKey(String qcloudSecretKey) {
        this.qcloudSecretKey = qcloudSecretKey;
    }

    public String getQcloudBucketName() {
        return qcloudBucketName;
    }

    public void setQcloudBucketName(String qcloudBucketName) {
        this.qcloudBucketName = qcloudBucketName;
    }

    public String getQcloudRegion() {
        return qcloudRegion;
    }

    public void setQcloudRegion(String qcloudRegion) {
        this.qcloudRegion = qcloudRegion;
    }
}

2、上传、下载文件


import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.GeneratePresignedUrlRequest;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.PutObjectRequest;
import com.qn.config.CloudStorageConfig;
import com.qn.config.GlobalValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.Date;

/**
 * 腾讯云上传下载工具
 * Created by Steve on 2018/10/11 0011.
 */
public class COSUtil {
    private static final Logger logger = LoggerFactory.getLogger(COSUtil.class);

    // 输出地址
    private static String downLoadFile = GlobalValue.outFilePath;

    private static CloudStorageConfig cloudStorageConfig = GlobalValue.cloudStorageConfig;

    private static COSClient cosClient = GlobalValue.cosClient;

    /**
     * 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20M以下的文件使用该接口
     *
     * @param file
     * @return
     */
    public static void uploadFile(File file) throws Exception {
        // 指定要上传到 COS 上对象键
        // 对象键(Key)是对象在存储桶中的唯一标识。例如,在对象的访问域名 `bucket1-1250000000.cos.ap-guangzhou.myqcloud.com/doc1/pic1.jpg` 中,对象键为 doc1/pic1.jpg, 详情参考 [对象键](https://cloud.tencent.com/document/product/436/13324)
        String key = file.getName();
        PutObjectRequest putObjectRequest = new PutObjectRequest(cloudStorageConfig.getQcloudBucketName(), key, file);
        cosClient.putObject(putObjectRequest);
        logger.info("{} 上传腾讯云完成", key);
    }

    /**
     * 获取腾讯云下载url
     *
     * @param key 文件名称:201810151649078611545515.pdf
     * @return
     */
    public static String getDownLoadUrl(String key) {
        // 设置URL过期时间为1小时 60*60*1000()
        Date expiration = new Date(new Date().getTime() + 60 * 60 * 1000);

        GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(cloudStorageConfig.getQcloudBucketName(), key);
        // 设置签名过期时间(可选), 若未进行设置, 则默认使用 ClientConfig 中的签名过期时间(5分钟)
        generatePresignedUrlRequest.setExpiration(expiration);
        String url = cosClient.generatePresignedUrl(generatePresignedUrlRequest).toString();
        logger.info("获取腾讯云签名:{}", url);
        return url;
    }

    /**
     * 下载文件
     *
     * @param fileName
     */
    public static void downFile(String fileName) {
        // 指定要下载到的本地路径
        String filePath = downLoadFile + "pdf/" + fileName;
        // 指定要下载的文件所在的 bucket 和对象键
        GetObjectRequest getObjectRequest = new GetObjectRequest(cloudStorageConfig.getQcloudBucketName(), fileName);
        cosClient.getObject(getObjectRequest, new File(filePath));
        logger.info("{} 腾讯云下载文件完成", fileName);
    }
}

 

你可能感兴趣的:(java工具类)