java 对接腾讯COS实现上传文件功能

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
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.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.wqh.fsrm.common.ResponseResult;
import com.wqh.fsrm.common.util.MD5Utils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.web.multipart.MultipartFile;

import java.net.URL;
import java.util.*;

public class CosFile {

    private static Logger log  = LoggerFactory.getLogger(CosFile.class);


    public static final String secretId = "";
    public static final String secretKey = "";
    public static final String bucket = "polz-files-1302700757";
    public static final String regionString = "ap-shanghai";
    public static final String url = "https://polz-files-1302700757.cos.ap-shanghai.myqcloud.com";

    public static COSClient getCOSClient(){
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        Region region = new Region(regionString);
        ClientConfig clientConfig = new ClientConfig(region);
        clientConfig.setHttpProtocol(HttpProtocol.https);
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }

    /**
     *
     * @param file 文件
     * @param contextType 文件类型
     * @param path 路径
     * @param
     * @return
     */
    public static JSONObject uploadFileToCos(MultipartFile file, String contextType, String path, String fileName) {
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(file.getSize());
        metadata.setContentType(contextType);
        try{
            COSClient cosClient = getCOSClient();
            PutObjectResult pubResult = cosClient.putObject(bucket, path + fileName, file.getInputStream(),metadata);
            if(pubResult == null || StringUtils.isBlank(pubResult.getETag())){
                log.error("upload to cos error, put object result is null or etag is empty,  fileName {}", fileName);
                return ResponseResult.failure("501","upload to cos error, put object result is null or etag is empty");
            }
            Map<String,Object> map = new HashMap<>();
            map.put("fileMd5",pubResult.getETag());
            map.put("url",url + "/" + path + fileName);
            return ResponseResult.success(map);
        }catch(Exception e){
            log.error("upload to cos error", e);
            return ResponseResult.failure("501",e.getMessage());

        }
    }



    /**
     * bucket设置为私有的时候,需要签名访问。该方法可以生成签名链接地址
     * @param file 文件
     * @param contextType 文件类型
     * @param path 路径
     * @param
     * @return
     */
    public static JSONObject uploadFileToCosSign(MultipartFile file, String contextType, String path, String fileName) {
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(file.getSize());
        metadata.setContentType(contextType);
        try{
            COSClient cosClient = getCOSClient();
            PutObjectResult pubResult = cosClient.putObject(bucket, path + fileName, file.getInputStream(),metadata);
            if(pubResult == null || StringUtils.isBlank(pubResult.getETag())){
                log.error("upload to cos error, put object result is null or etag is empty,  fileName {}", fileName);
                return ResponseResult.failure("501","upload to cos error, put object result is null or etag is empty");
            }
            String url = getSignUrl(path,fileName);
            Map<String,Object> map = new HashMap<>();
            map.put("fileMd5",pubResult.getETag());
            map.put("url",url);
            return ResponseResult.success(map);
        }catch(Exception e){
            log.error("upload to cos error", e);
            return ResponseResult.failure("501",e.getMessage());

        }
    }
    /**
     * 根据文件路径重新生成文件名,文件名后缀为oldFilePath的后缀
     *
     * @param oldFilePath
     * @return
     */
    public static String getFileName(String oldFilePath){
        String newFileName = MD5Utils.encrypt(UUID.randomUUID().toString());
        if(oldFilePath.lastIndexOf(".") >=0){
            newFileName = newFileName + oldFilePath.substring(oldFilePath.lastIndexOf("."));
        }
        return newFileName;
    }


    public static String getSignUrl(String path,String fileName){
        // 调用 COS 接口之前必须保证本进程存在一个 COSClient 实例,如果没有则创建
// 详细代码参见本页:简单操作 -> 创建 COSClient
        COSClient cosClient = getCOSClient();

// 存储桶的命名格式为 BucketName-APPID,此处填写的存储桶名称必须为此格式
        String bucketName = bucket;
// 对象键(Key)是对象在存储桶中的唯一标识。详情请参见 [对象键](https://cloud.tencent.com/document/product/436/13324)
        String key = path+fileName;

// 设置签名过期时间(可选), 若未进行设置则默认使用 ClientConfig 中的签名过期时间(1小时)
// 这里设置签名在半个小时后过期
        Date expirationDate = new Date(System.currentTimeMillis() + 30 * 60 * 1000);

// 填写本次请求的参数,需与实际请求相同,能够防止用户篡改此签名的 HTTP 请求的参数
        Map<String, String> params = new HashMap<String, String>();
        params.put("param1", "value1");

// 填写本次请求的头部,需与实际请求相同,能够防止用户篡改此签名的 HTTP 请求的头部
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("header1", "value1");

// 请求的 HTTP 方法,上传请求用 PUT,下载请求用 GET,删除请求用 DELETE
        HttpMethodName method = HttpMethodName.GET;

        URL url = cosClient.generatePresignedUrl(bucketName, key, expirationDate, method, headers, params);

        return url.toString();
    }
}

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浮生若梦01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值