Search in sources :

Example 26 with PutObjectResult

use of com.qcloud.cos.model.PutObjectResult in project roof-im by madfroglx.

the class OCSTest method testUpload.

@Test
public void testUpload() {
    // 用户基本信息
    String appid = "1255710173";
    String secret_id = "AKID3A9jOoqatjrh6k7UjyKfA5N6q4olSaB6";
    String secret_key = "Qdr0efEb3NicSkED2UsKaQ8ANaPorDWr";
    String sessionToken = "81ca8cc5fb84bd42ac36c40515917b308ad333d830001";
    // 设置秘钥
    COSCredentials cred = new BasicCOSCredentials(appid, secret_id, secret_key);
    // 设置区域, 这里设置为华北
    ClientConfig clientConfig = new ClientConfig(new Region("ap-shanghai"));
    // 生成 cos 客户端对象
    COSClient cosClient = new COSClient(cred, clientConfig);
    // 创建 bucket
    // bucket 数量上限 200 个, bucket 是重操作, 一般不建议创建如此多的 bucket
    // 重复创建同名 bucket 会报错
    String bucketName = "im";
    // 上传 object, 建议 20M 以下的文件使用该接口
    File localFile = new File("E:\\excel\\test.txt");
    String key = "im/zlt/test4";
    PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
    ObjectMetadata objectMetadata = new ObjectMetadata();
    objectMetadata.setSecurityToken(sessionToken);
    putObjectRequest.setMetadata(objectMetadata);
    PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
    System.out.println(putObjectResult);
    // 关闭客户端 (关闭后台线程)
    cosClient.shutdown();
}
Also used : COSClient(com.qcloud.cos.COSClient) COSCredentials(com.qcloud.cos.auth.COSCredentials) BasicCOSCredentials(com.qcloud.cos.auth.BasicCOSCredentials) BasicCOSCredentials(com.qcloud.cos.auth.BasicCOSCredentials) PutObjectResult(com.qcloud.cos.model.PutObjectResult) Region(com.qcloud.cos.region.Region) ClientConfig(com.qcloud.cos.ClientConfig) File(java.io.File) ObjectMetadata(com.qcloud.cos.model.ObjectMetadata) PutObjectRequest(com.qcloud.cos.model.PutObjectRequest) Test(org.junit.Test)

Example 27 with PutObjectResult

use of com.qcloud.cos.model.PutObjectResult in project halo by ruibaby.

the class TencentCosFileHandler method upload.

@Override
public UploadResult upload(MultipartFile file) {
    Assert.notNull(file, "Multipart file must not be null");
    // Get config
    String protocol = optionService.getByPropertyOfNonNull(TencentCosProperties.COS_PROTOCOL).toString();
    String domain = optionService.getByPropertyOrDefault(TencentCosProperties.COS_DOMAIN, String.class, "");
    String region = optionService.getByPropertyOfNonNull(TencentCosProperties.COS_REGION).toString();
    String secretId = optionService.getByPropertyOfNonNull(TencentCosProperties.COS_SECRET_ID).toString();
    String secretKey = optionService.getByPropertyOfNonNull(TencentCosProperties.COS_SECRET_KEY).toString();
    String bucketName = optionService.getByPropertyOfNonNull(TencentCosProperties.COS_BUCKET_NAME).toString();
    String source = optionService.getByPropertyOrDefault(TencentCosProperties.COS_SOURCE, String.class, "");
    String styleRule = optionService.getByPropertyOrDefault(TencentCosProperties.COS_STYLE_RULE, String.class, "");
    String thumbnailStyleRule = optionService.getByPropertyOrDefault(TencentCosProperties.COS_THUMBNAIL_STYLE_RULE, String.class, "");
    COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
    Region regionConfig = new Region(region);
    ClientConfig clientConfig = new ClientConfig(regionConfig);
    // Init OSS client
    COSClient cosClient = new COSClient(cred, clientConfig);
    StringBuilder basePath = new StringBuilder(protocol);
    if (StringUtils.isNotEmpty(domain)) {
        basePath.append(domain).append(URL_SEPARATOR);
    } else {
        basePath.append(bucketName).append(".cos.").append(region).append(".myqcloud.com").append(URL_SEPARATOR);
    }
    try {
        FilePathDescriptor pathDescriptor = new FilePathDescriptor.Builder().setBasePath(basePath.toString()).setSubPath(source).setAutomaticRename(true).setRenamePredicate(relativePath -> attachmentRepository.countByFileKeyAndType(relativePath, AttachmentType.TENCENTCOS) > 0).setOriginalName(file.getOriginalFilename()).build();
        // Upload
        ObjectMetadata objectMetadata = new ObjectMetadata();
        // 提前告知输入流的长度, 否则可能导致 oom
        objectMetadata.setContentLength(file.getSize());
        // 设置 Content type, 默认是 application/octet-stream
        objectMetadata.setContentType(file.getContentType());
        PutObjectResult putObjectResponseFromInputStream = cosClient.putObject(bucketName, pathDescriptor.getRelativePath(), file.getInputStream(), objectMetadata);
        if (putObjectResponseFromInputStream == null) {
            throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到腾讯云失败 ");
        }
        String fullPath = pathDescriptor.getFullPath();
        // Response result
        UploadResult uploadResult = new UploadResult();
        uploadResult.setFilename(pathDescriptor.getName());
        uploadResult.setFilePath(StringUtils.isBlank(styleRule) ? fullPath : fullPath + styleRule);
        uploadResult.setKey(pathDescriptor.getRelativePath());
        uploadResult.setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType())));
        uploadResult.setSuffix(pathDescriptor.getExtension());
        uploadResult.setSize(file.getSize());
        // Handle thumbnail
        handleImageMetadata(file, uploadResult, () -> {
            if (ImageUtils.EXTENSION_ICO.equals(pathDescriptor.getExtension())) {
                uploadResult.setThumbPath(fullPath);
                return fullPath;
            } else {
                return StringUtils.isBlank(thumbnailStyleRule) ? fullPath : fullPath + thumbnailStyleRule;
            }
        });
        return uploadResult;
    } catch (Exception e) {
        throw new FileOperationException("附件 " + file.getOriginalFilename() + " 上传失败(腾讯云)", e);
    } finally {
        cosClient.shutdown();
    }
}
Also used : COSCredentials(com.qcloud.cos.auth.COSCredentials) BasicCOSCredentials(com.qcloud.cos.auth.BasicCOSCredentials) BasicCOSCredentials(com.qcloud.cos.auth.BasicCOSCredentials) PutObjectResult(com.qcloud.cos.model.PutObjectResult) FileOperationException(run.halo.app.exception.FileOperationException) FileOperationException(run.halo.app.exception.FileOperationException) COSClient(com.qcloud.cos.COSClient) Region(com.qcloud.cos.region.Region) UploadResult(run.halo.app.model.support.UploadResult) ClientConfig(com.qcloud.cos.ClientConfig) ObjectMetadata(com.qcloud.cos.model.ObjectMetadata)

Example 28 with PutObjectResult

use of com.qcloud.cos.model.PutObjectResult in project jeesuite-libs by vakinge.

the class QcloudProvider method upload.

@Override
public CUploadResult upload(CUploadObject object) {
    PutObjectRequest request;
    String fileKey = object.getFileKey();
    String bucketName = buildBucketName(object.getBucketName());
    if (object.getFile() != null) {
        request = new PutObjectRequest(bucketName, fileKey, object.getFile());
    } else if (object.getBytes() != null) {
        ByteArrayInputStream inputStream = new ByteArrayInputStream(object.getBytes());
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(object.getFileSize());
        request = new PutObjectRequest(bucketName, fileKey, inputStream, objectMetadata);
    } else if (object.getInputStream() != null) {
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(object.getFileSize());
        request = new PutObjectRequest(bucketName, fileKey, object.getInputStream(), objectMetadata);
    } else {
        throw new IllegalArgumentException("upload object is NULL");
    }
    try {
        if (object.getFileSize() > conf.getMaxAllowdSingleFileSize()) {
            Upload upload = transferManager.upload(request);
            com.qcloud.cos.model.UploadResult result = upload.waitForUploadResult();
            return new CUploadResult(fileKey, getFullPath(object.getBucketName(), fileKey), result.getCrc64Ecma());
        } else {
            PutObjectResult result = cosclient.putObject(request);
            return new CUploadResult(fileKey, getFullPath(object.getBucketName(), fileKey), result.getContentMd5());
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new JeesuiteBaseException(500, buildMessage(bucketName, e));
    }
}
Also used : PutObjectResult(com.qcloud.cos.model.PutObjectResult) Upload(com.qcloud.cos.transfer.Upload) CosServiceException(com.qcloud.cos.exception.CosServiceException) IOException(java.io.IOException) JeesuiteBaseException(com.jeesuite.common.JeesuiteBaseException) CUploadResult(com.jeesuite.cos.CUploadResult) JeesuiteBaseException(com.jeesuite.common.JeesuiteBaseException) ByteArrayInputStream(java.io.ByteArrayInputStream) ObjectMetadata(com.qcloud.cos.model.ObjectMetadata) CObjectMetadata(com.jeesuite.cos.CObjectMetadata) PutObjectRequest(com.qcloud.cos.model.PutObjectRequest)

Example 29 with PutObjectResult

use of com.qcloud.cos.model.PutObjectResult in project cos-java-sdk-v5 by tencentyun.

the class PutObjectCopyTest method testCopySameRegionDiffSize.

private void testCopySameRegionDiffSize(long fileSize, ObjectMetadata newObjectMetaData) throws IOException {
    if (!judgeUserInfoValid()) {
        return;
    }
    File localFile = buildTestFile(fileSize);
    String srcEtag = Md5Utils.md5Hex(localFile);
    String srcKey = String.format("ut/src_len_%d.txt", fileSize);
    String destKey = String.format("ut/dest_len_%d.txt", fileSize);
    try {
        PutObjectResult putObjectResult = putObjectFromLocalFile(localFile, srcKey);
        CopyObjectRequest copyObjectRequest = new CopyObjectRequest(bucket, srcKey, bucket, destKey);
        copyObjectRequest.setSourceVersionId(putObjectResult.getVersionId());
        copyObjectRequest.setStorageClass(StorageClass.Standard_IA);
        if (newObjectMetaData != null) {
            copyObjectRequest.setNewObjectMetadata(newObjectMetaData);
        }
        CopyObjectResult copyObjectResult = cosclient.copyObject(copyObjectRequest);
        assertNotNull(copyObjectResult.getRequestId());
        assertNotNull(copyObjectResult.getDateStr());
        // assertEquals(srcEtag, copyObjectResult.getETag());
        headSimpleObject(srcKey, fileSize, srcEtag);
    /*
            ObjectMetadata destObjectMetadata = headSimpleObject(destKey, fileSize, srcEtag);
            if (newObjectMetaData != null) {
                checkMetaData(newObjectMetaData, destObjectMetadata);
            }
            */
    } finally {
        // delete file on cos
        clearObject(srcKey);
        clearObject(destKey);
        // delete local file
        if (localFile.exists()) {
            assertTrue(localFile.delete());
        }
    }
}
Also used : CopyObjectRequest(com.qcloud.cos.model.CopyObjectRequest) PutObjectResult(com.qcloud.cos.model.PutObjectResult) CopyObjectResult(com.qcloud.cos.model.CopyObjectResult) File(java.io.File)

Example 30 with PutObjectResult

use of com.qcloud.cos.model.PutObjectResult in project cos-java-sdk-v5 by tencentyun.

the class CAMRoleDemo method SimpleUploadFileFromEMR.

public static void SimpleUploadFileFromEMR() {
    InstanceMetadataCredentialsEndpointProvider endpointProvider = new InstanceMetadataCredentialsEndpointProvider(InstanceMetadataCredentialsEndpointProvider.Instance.EMR);
    InstanceCredentialsFetcher instanceCredentialsFetcher = new InstanceCredentialsFetcher(endpointProvider);
    COSCredentialsProvider cosCredentialsProvider = new InstanceCredentialsProvider(instanceCredentialsFetcher);
    COSCredentials cred = cosCredentialsProvider.getCredentials();
    System.out.println(cred.getCOSAccessKeyId());
    System.out.println(cred.getCOSSecretKey());
    System.out.println(cred.getCOSAppId());
    ClientConfig clientConfig = new ClientConfig(new Region("ap-chongqing"));
    COSClient cosClient = new COSClient(cosCredentialsProvider, clientConfig);
    String bucketName = "aaa-125xxx";
    String key = "test_emr.txt";
    File localFile = new File("./test");
    PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
    putObjectRequest.setStorageClass(StorageClass.Standard);
    PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
    System.out.println("upload file etag: " + putObjectResult.getETag());
    System.out.println("upload file requestId: " + putObjectResult.getRequestId());
    ObjectMetadata getMeta = cosClient.getObjectMetadata(bucketName, key);
    System.out.println("get file etag: " + getMeta.getETag());
    cosClient.deleteObject(bucketName, key);
    if (cosClient.doesObjectExist(bucketName, key)) {
        System.out.println("delete failed");
    } else {
        System.out.println("delete successfully");
    }
    cosClient.shutdown();
}
Also used : PutObjectResult(com.qcloud.cos.model.PutObjectResult) COSClient(com.qcloud.cos.COSClient) Region(com.qcloud.cos.region.Region) ClientConfig(com.qcloud.cos.ClientConfig) File(java.io.File) ObjectMetadata(com.qcloud.cos.model.ObjectMetadata) PutObjectRequest(com.qcloud.cos.model.PutObjectRequest)

Aggregations

PutObjectResult (com.qcloud.cos.model.PutObjectResult)34 PutObjectRequest (com.qcloud.cos.model.PutObjectRequest)22 File (java.io.File)21 COSClient (com.qcloud.cos.COSClient)14 ClientConfig (com.qcloud.cos.ClientConfig)14 Region (com.qcloud.cos.region.Region)14 BasicCOSCredentials (com.qcloud.cos.auth.BasicCOSCredentials)11 COSCredentials (com.qcloud.cos.auth.COSCredentials)11 CosServiceException (com.qcloud.cos.exception.CosServiceException)11 ObjectMetadata (com.qcloud.cos.model.ObjectMetadata)11 CosClientException (com.qcloud.cos.exception.CosClientException)10 CIObject (com.qcloud.cos.model.ciModel.persistence.CIObject)4 CIUploadResult (com.qcloud.cos.model.ciModel.persistence.CIUploadResult)4 PicOperations (com.qcloud.cos.model.ciModel.persistence.PicOperations)4 IOException (java.io.IOException)4 LinkedList (java.util.LinkedList)4 Test (org.junit.Test)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 InputStream (java.io.InputStream)3 FileOperationException (run.halo.app.exception.FileOperationException)3