腾讯云COS上传文件出现数据损坏问题

问题:

桶中能正常接收到文件,但是文件出现数据损坏,控制台报错为

No content length specified for stream data. Stream contents will be buffered in memory and could result in out of memory errors.

解决办法 :

给metadata的ContentLength属性赋值所要传输文件字节流的字节数.

ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(byteArrayInputStream.available());

另外COS上传文件的工具类分享给大家.

@Component
@ConfigurationProperties(prefix = "tencent")
@Data
public class TencentCosProperties {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
}
=======================================================
@Configuration
@Slf4j
public class CosConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public TencentCosUtil tencentCosUtil(TencentCosProperties tencentCosProperties){
        return new TencentCosUtil(
                tencentCosProperties.getEndpoint(),
                tencentCosProperties.getAccessKeyId(),
                tencentCosProperties.getAccessKeySecret(),
                tencentCosProperties.getBucketName());
    }
}
=======================================================
@Data
@AllArgsConstructor
@Slf4j
public class TencentCosUtil {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    /**
     * 文件上传
     *
     * @param bytes 文件byte数组
     * @param objectName   文件名称
     * @return
     */
    public String upload(byte[] bytes, String objectName) {

        // 创建OSSClient实例。
        COSCredentials cred = new BasicCOSCredentials(accessKeyId, accessKeySecret);
        Region region = new Region(com.tencentcloudapi.common.profile.Region.Guangzhou.toString());
        ClientConfig clientConfig = new ClientConfig(region);
        clientConfig.setHttpProtocol(HttpProtocol.https);
        COSClient cosClient = new COSClient(cred, clientConfig);

        String folder = "images/";
        String key = folder + objectName;
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType("image/png");
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        metadata.setContentLength(byteArrayInputStream.available());
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, byteArrayInputStream, metadata);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);

        //文件访问路径规则 https://BucketName.Endpoint/ObjectName
        StringBuilder stringBuilder = new StringBuilder("");
        stringBuilder
                .append(endpoint)
                .append("/")
                .append(key);

        log.info("文件上传到:{}", stringBuilder.toString());
        cosClient.shutdown();
        return stringBuilder.toString();
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用腾讯云官方提供的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返回给前端。 希望以上信息能对你有所帮助。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值