Java接入腾讯云COS 实现文件上传

1、POM依赖

<!--腾讯云COS-->
        <dependency>
            <groupId>com.tencentcloudapi</groupId>
            <artifactId>tencentcloud-sdk-java</artifactId>
            <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.qcloud</groupId>
            <artifactId>cos_api</artifactId>
            <version>5.4.9</version>
        </dependency>

2、涉及代码

2.1 配置类

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @Description 腾讯云COS相关配置文件
 * @Author Jason
 * @Date 2020/3/5 16:22
 * @Email jasonaszp@163.com
 */
@Data
@ConfigurationProperties(prefix = "tencentcos")
@Component
public class TencentCosConfig {
    //腾讯云的SecretId
    private String secretId;
    //腾讯云的SecretKey
    private String secretKey;
    //腾讯云的bucket (存储桶)
    private String bucket;
    //腾讯云的region(bucket所在地区)
    private String region;
    //腾讯云的allowPrefix(允许上传的路径)
    private String allowPrefix = "*";
    //腾讯云的临时密钥时长(单位秒)
    private String durationSeconds;
    //腾讯云的访问基础链接:
    private String baseUrl;
}

 2.2 具体上传逻辑代码

import com.etc.insurance.config.TencentCosConfig;
import com.etc.util.EtcSpringUtils;
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.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.StorageClass;
import com.qcloud.cos.region.Region;

import java.io.*;

 /**
 * @Description 腾讯云cos服务器上传工具类
 * @Author Jason
 * @Date 2020/3/6 14:30
 * @Email jasonaszp@163.com
 */
public class TencentUploadUtil {

    //腾讯云的SecretId
    private static String secretId;
    //腾讯云的SecretKey
    private static String secretKey;
    //腾讯云的bucket (存储桶)
    private static String bucket;
    //腾讯云的region(bucket所在地区)
    private static String region;
    //腾讯云的allowPrefix(允许上传的路径)
    private static String allowPrefix;
    //腾讯云的临时密钥时长(单位秒)
    private static String durationSeconds;
    //腾讯云的访问基础链接:
    private static String baseUrl;
    // 腾讯云cos相关配置类
    private static TencentCosConfig tencentCosConfig;

    //初始化配置
    static {
        tencentCosConfig = EtcSpringUtils.getBean(TencentCosConfig.class);
        secretId = tencentCosConfig.getSecretId();
        secretKey = tencentCosConfig.getSecretKey();
        bucket = tencentCosConfig.getBucket();
        region = tencentCosConfig.getRegion();
        allowPrefix = tencentCosConfig.getAllowPrefix();
        durationSeconds = tencentCosConfig.getDurationSeconds();
        baseUrl = tencentCosConfig.getBaseUrl();
    }

    /**
     * 上传腾讯云
     *
     * @param bytes    文件字节
     * @param filePath 文件路径
     * @return 腾讯云访问路径
     */
    public static String upload(byte[] bytes, String filePath) {
        // 1 初始化秘钥信息
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2 设置bucket的区域
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        // 3 生成cos客户端
        COSClient cosClient = new COSClient(cred, clientConfig);

        // 处理文件路径
        filePath = filePath.startsWith("/") ? filePath : "/" + filePath;

        // 判断文件大小(小文件上传建议不超过20M)
        int length = bytes.length;
        // 获取文件流
        InputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        ObjectMetadata objectMetadata = new ObjectMetadata();
        // 从输入流上传必须制定content length, 否则http客户端可能会缓存所有数据,存在内存OOM的情况
        objectMetadata.setContentLength(length);
        // 默认下载时根据cos路径key的后缀返回响应的contenttype, 上传时设置contenttype会覆盖默认值
        // objectMetadata.setContentType("image/jpeg");

        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, filePath, byteArrayInputStream, objectMetadata);
        // 设置 Content type, 默认是 application/octet-stream
        putObjectRequest.setMetadata(objectMetadata);
        // 设置存储类型, 默认是标准(Standard), 低频(standard_ia)
        putObjectRequest.setStorageClass(StorageClass.Standard_IA);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);

        String eTag = putObjectResult.getETag();
        System.out.println(eTag);
        // 关闭客户端
        cosClient.shutdown();
        // http://{buckname}-{appid}.cosgz.myqcloud.com/image/1545012027692.jpg
        return baseUrl + filePath;
    }

    /**
     * 上传腾讯云
     *
     * @param file     文件
     * @param filePath 文件路径
     * @return 腾讯云访问路径
     */
    public static String upload(File file, String filePath) {
        // 1 初始化秘钥信息
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        // 3 生成cos客户端
        COSClient cosClient = new COSClient(cred, clientConfig);

        // 处理文件路径
        filePath = filePath.startsWith("/") ? filePath : "/" + filePath;

        // 判断文件大小(小文件上传建议不超过20M)
        byte[] bytes = File2byte(file);
        int length = bytes.length;
        // 获取文件流
        InputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        ObjectMetadata objectMetadata = new ObjectMetadata();
        // 从输入流上传必须制定content length, 否则http客户端可能会缓存所有数据,存在内存OOM的情况
        objectMetadata.setContentLength(length);
        // 默认下载时根据cos路径key的后缀返回响应的contenttype, 上传时设置contenttype会覆盖默认值
        // objectMetadata.setContentType("image/jpeg");

        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, filePath, byteArrayInputStream, objectMetadata);
        // 设置 Content type, 默认是 application/octet-stream
        putObjectRequest.setMetadata(objectMetadata);
        // 设置存储类型, 默认是标准(Standard), 低频(standard_ia)
        putObjectRequest.setStorageClass(StorageClass.Standard_IA);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);

        String eTag = putObjectResult.getETag();
        System.out.println(eTag);
        // 关闭客户端
        cosClient.shutdown();
        // http://{buckname}-{appid}.cosgz.myqcloud.com/image/1545012027692.jpg
        return baseUrl + filePath;
    }

    public static byte[] File2byte(File tradeFile) {
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(tradeFile);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }
}

 

 

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
可以使用腾讯云官方提供的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、付费专栏及课程。

余额充值