All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.hn.upload.TencentUpload Maven / Gradle / Ivy

There is a newer version: 1.0.18
Show newest version
package com.hn.upload;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.aliyun.oss.OSS;
import com.hn.config.HnConfigUtils;
import com.hn.config.exception.ConfigException;
import com.hn.utils.AssertUtils;
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.HttpMethodName;
import com.qcloud.cos.model.GeneratePresignedUrlRequest;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.tencent.cloud.CosStsClient;
import lombok.Data;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.TreeMap;

/**
 * 腾讯云上传
 * api: https://cloud.tencent.com/document/product/436/7751
 * java sdk: https://cloud.tencent.com/document/product/436/10199
 */
public class TencentUpload extends AbstractFileUpload {

    private static final Log log = LogFactory.get();

    private Param param;

    public static Param createParam() {
        return new Param();
    }

    public TencentUpload(Param param) {
        checkParam(param);
        this.param = param;
    }

    public TencentUpload(String scene) {
        Param param = getRequestParam(scene);
        checkParam(param);
        this.param = param;
    }

    @Override
    public String getFileBaseUrl() {
        return param.fileUrl;
    }

    /**
     * 获取文件临时下载地址
     *
     * @param key        文件key(路径)
     * @param expireTime 过期时间 以分为单位
     *                   设置签名过期时间(可选), 若未进行设置, 则默认使用 ClientConfig 中的签名过期时间(1小时)
     * @return 下载地址
     */
    @Override
    public String getTempDownUrl(String key, Integer expireTime) {
        COSClient cosClient = getCOSClient();
        GeneratePresignedUrlRequest req =
                new GeneratePresignedUrlRequest(param.bucket, key, HttpMethodName.GET);
        if (expireTime != null && expireTime != 0) {
            Date expirationDate = new Date(System.currentTimeMillis() + expireTime * 60L * 1000L);
            req.setExpiration(expirationDate);
        }
        URL url = cosClient.generatePresignedUrl(req);
        return String.valueOf(url);
    }

    /**
     * 获取临时密钥
     * 获取临时密钥文档
     * cos-sts-sdk 源码
     *
     * @return obj 临时密钥
     */
    @Override
    public Object getToken() {
        return getToken("*");
    }

    @Override
    public Object getToken(String dir) {
        TreeMap config = new TreeMap<>();
        try {
            // 替换为您的 SecretId
            config.put("SecretId", param.secretId);
            // 替换为您的 SecretKey
            config.put("SecretKey", param.secretKey);
            // 临时密钥有效时长,单位是秒,默认1800秒,最长可设定有效期为7200秒
            config.put("durationSeconds", 1800);
            // 换成您的 bucket
            config.put("bucket", param.bucket);
            // 换成 bucket 所在地区
            config.put("region", param.region);

            // 这里改成允许的路径前缀,可以根据自己网站的用户登录态判断允许上传的具体路径,例子:a.jpg 或者 a/* 或者 * 。
            // 如果填写了“*”,将允许用户访问所有资源;除非业务需要,否则请按照最小权限原则授予用户相应的访问权限范围。
            config.put("allowPrefix", dir);

            // 密钥的权限列表。简单上传、表单上传和分片上传需要以下的权限,其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
            String[] allowActions = new String[]{
                    // 简单上传
                    "name/cos:PutObject",
                    // 表单上传、小程序上传
                    "name/cos:PostObject",
                    // 分片上传
                    "name/cos:InitiateMultipartUpload",
                    "name/cos:ListMultipartUploads",
                    "name/cos:ListParts",
                    "name/cos:UploadPart",
                    "name/cos:CompleteMultipartUpload"
            };
            config.put("allowActions", allowActions);

            JSONObject credential = CosStsClient.getCredential(config);
            //成功返回临时密钥信息,如下打印密钥信息
            log.info("腾讯云返回密钥:{}", credential);
            return credential;
        } catch (IOException e) {
            //失败抛出异常
            throw new UploadException("腾讯云获取临时授权码失败 : no valid secret !");
        }
    }

    @Override
    public String uploadFile(File file, String objectName) {
        COSClient cosClient = getCOSClient();
        PutObjectRequest putObjectRequest = new PutObjectRequest(param.bucket, objectName, file);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        log.info("腾讯云存储返回结果:{}", JSONUtil.toJsonStr(putObjectResult));
        return objectName;
    }

    @Override
    public String uploadFile(InputStream is, String objectName) {
        COSClient cosClient = getCOSClient();
        PutObjectRequest putObjectRequest = new PutObjectRequest(param.bucket, objectName, is, null);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        log.info("腾讯云存储返回结果:{}", JSONUtil.toJsonStr(putObjectResult));
        return objectName;
    }

    @Override
    public void deleteFile(String key) {
        COSClient cosClient = getCOSClient();
        cosClient.deleteObject(param.bucket, key);
    }

    /**
     * 初始化用户身份信息(secretId, secretKey)
     *
     * @return COSCredentials
     */
    private COSCredentials getCOSCredentials() {
        String secretId = param.secretId;
        String secretKey = param.secretKey;
        return new BasicCOSCredentials(secretId, secretKey);
    }

    /**
     * 生成 cos 客户端
     *
     * @return COSClient
     */
    private COSClient getCOSClient() {
        Region region = new Region(param.region);
        ClientConfig clientConfig = new ClientConfig(region);
        return new COSClient(getCOSCredentials(), clientConfig);
    }

    /**
     * 配置前缀名
     */
    private static final String CONFIG_KEY = "upload.tencent";

    /**
     * 获取数据配置
     *
     * @return Param
     */
    private Param getRequestParam(String scene) {
        String configKey = CONFIG_KEY;
        if (StrUtil.isNotBlank(scene)) {
            configKey = configKey.concat("-").concat(scene);
        }

        String accessKey = HnConfigUtils.getConfig(configKey.concat(".secretId"));
        String secretKey = HnConfigUtils.getConfig(configKey.concat(".secretKey"));
        String bucket = HnConfigUtils.getConfig(configKey.concat(".bucket"));
        String fileUrl = HnConfigUtils.getConfig(configKey.concat(".fileUrl"));
        String region = HnConfigUtils.getConfig(configKey.concat(".region"));

        Param param = new Param();
        param.setSecretId(accessKey);
        param.setSecretKey(secretKey);
        param.setBucket(bucket);
        param.setFileUrl(fileUrl);
        param.setRegion(region);
        return param;
    }

    private void checkParam(Param param) {
        AssertUtils.notNull(param, "param is null");
        AssertUtils.notNull(param.secretId,
                ConfigException.exception("腾讯云存储secretId未配置"));
        AssertUtils.notNull(param.secretKey,
                ConfigException.exception("腾讯云存储secretKey未配置"));
        AssertUtils.notNull(param.region,
                ConfigException.exception("腾讯云存储region未配置"));
        AssertUtils.notNull(param.bucket,
                ConfigException.exception("腾讯云存储bucket未配置"));
        AssertUtils.notNull(param.fileUrl,
                ConfigException.exception("腾讯云存储fileUrl未配置"));
    }

    @Data
    public static class Param {
        /**
         * 【腾讯云存储】secretId
         */
        private String secretId;
        /**
         * 【腾讯云存储】secretKey
         */
        private String secretKey;
        /**
         * 【腾讯云存储】region
         */
        private String region;
        /**
         * 【腾讯云存储】存储桶
         */
        private String bucket;
        /**
         * 【腾讯云存储】fileUrl
         */
        private String fileUrl;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy