Search in sources :

Example 26 with PutObjectRequest

use of com.qcloud.cos.model.PutObjectRequest in project e3mall by colg-cloud.

the class TencentCosTest method testName.

@Test
public void testName() {
    COSCredentials cred = new BasicCOSCredentials("AKIDUvjV6VEvvjS4Vliw360iEYpvpgMrqMKF", "sY3NVSL8kLk8KK8lIftzud9VggU5Vkne");
    // 采用了新的region名字,可用region的列表可以在官网文档中获取,也可以参考下面的XML SDK和JSON SDK的地域对照表
    ClientConfig clientConfig = new ClientConfig(new Region("ap-guangzhou"));
    COSClient cosclient = new COSClient(cred, clientConfig);
    // bucket的名字需要的包含appId
    String bucketName = "colg-1256242877";
    // 上传文件
    File localFile = new File(PROJECT_PATH + "\\src\\test\\resources\\images\\FastDfs架构.png");
    String key = "colg.png";
    PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
    // 设置存储类型, 默认是标准(Standard), 低频(standard_ia)
    putObjectRequest.setStorageClass(StorageClass.Standard);
    PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
    // putObjectResult会返回文件的etag
    String etag = putObjectResult.getETag();
    log.info("etag: {}", etag);
    // 关闭客户端
    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) PutObjectRequest(com.qcloud.cos.model.PutObjectRequest) BaseTest(cn.e3mall.common.tencent.cos.BaseTest) Test(org.junit.Test)

Example 27 with PutObjectRequest

use of com.qcloud.cos.model.PutObjectRequest 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) JeesuiteBaseException(com.mendmix.common.JeesuiteBaseException) IOException(java.io.IOException) CUploadResult(com.mendmix.cos.CUploadResult) JeesuiteBaseException(com.mendmix.common.JeesuiteBaseException) ByteArrayInputStream(java.io.ByteArrayInputStream) CObjectMetadata(com.mendmix.cos.CObjectMetadata) ObjectMetadata(com.qcloud.cos.model.ObjectMetadata) PutObjectRequest(com.qcloud.cos.model.PutObjectRequest)

Example 28 with PutObjectRequest

use of com.qcloud.cos.model.PutObjectRequest in project RuleApi by buxia97.

the class UploadController method cosUpload.

/**
 * 上传cos
 * @return
 */
@RequestMapping(value = "/cosUpload", method = RequestMethod.POST)
@ResponseBody
public Object cosUpload(@RequestParam(value = "file") MultipartFile file, @RequestParam(value = "token", required = false) String token) throws IOException {
    Integer uStatus = UStatus.getStatus(token, this.dataprefix, redisTemplate);
    if (uStatus == 0) {
        return Result.getResultJson(0, "用户未登录或Token验证失败", null);
    }
    if (file == null) {
        return new UploadMsg(0, "文件为空", null);
    }
    TypechoApiconfig apiconfig = apiconfigService.selectByKey(1);
    String oldFileName = file.getOriginalFilename();
    // String eName = oldFileName.substring(oldFileName.lastIndexOf("."));
    String eName = "";
    try {
        eName = oldFileName.substring(oldFileName.lastIndexOf("."));
    } catch (Exception e) {
        oldFileName = oldFileName + ".png";
        eName = oldFileName.substring(oldFileName.lastIndexOf("."));
    }
    // 检查是否是图片
    BufferedImage bi = ImageIO.read(file.getInputStream());
    if (bi == null) {
        return Result.getResultJson(0, "请上传图片文件", null);
    }
    String newFileName = UUID.randomUUID() + eName;
    Calendar cal = Calendar.getInstance();
    int year = cal.get(Calendar.YEAR);
    int month = cal.get(Calendar.MONTH);
    int day = cal.get(Calendar.DATE);
    // 1 初始化用户身份信息(secretId, secretKey)
    COSCredentials cred = new BasicCOSCredentials(apiconfig.getCosAccessKey(), apiconfig.getCosSecretKey());
    // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
    ClientConfig clientConfig = new ClientConfig(new Region(apiconfig.getCosBucket()));
    // 3 生成cos客户端
    COSClient cosclient = new COSClient(cred, clientConfig);
    // bucket的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
    String bucketName = apiconfig.getCosBucketName();
    // 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20 M 以下的文件使用该接口
    // 大文件上传请参照 API 文档高级 API 上传
    File localFile = null;
    try {
        localFile = File.createTempFile("temp", null);
        file.transferTo(localFile);
        // 指定要上传到 COS 上的路径
        String key = "/" + apiconfig.getCosPrefix() + "/" + year + "/" + month + "/" + day + "/" + newFileName;
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
        PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
        // return new UploadMsg(1,"上传成功",this.path + putObjectRequest.getKey());
        Map<String, String> info = new HashMap<String, String>();
        info.put("url", apiconfig.getCosPath() + putObjectRequest.getKey());
        return Result.getResultJson(1, "上传成功", info);
    } catch (IOException e) {
        return Result.getResultJson(0, "上传失败", null);
    } 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) HashMap(java.util.HashMap) Calendar(java.util.Calendar) BufferedImage(java.awt.image.BufferedImage) COSClient(com.qcloud.cos.COSClient) Region(com.qcloud.cos.region.Region) ClientConfig(com.qcloud.cos.ClientConfig) TypechoApiconfig(com.RuleApi.entity.TypechoApiconfig) MultipartFile(org.springframework.web.multipart.MultipartFile) PutObjectRequest(com.qcloud.cos.model.PutObjectRequest) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 29 with PutObjectRequest

use of com.qcloud.cos.model.PutObjectRequest in project hadoop-cos by tencentyun.

the class CosNativeFileSystemStore method storeEmptyFile.

// for cos, storeEmptyFile means create a directory
@Override
public void storeEmptyFile(String key) throws IOException {
    LOG.debug("Store an empty file to the key: {}.", key);
    ObjectMetadata objectMetadata = new ObjectMetadata();
    objectMetadata.setContentLength(0);
    if (crc32cEnabled) {
        objectMetadata.setHeader(Constants.CRC32C_REQ_HEADER, Constants.CRC32C_REQ_HEADER_VAL);
    }
    InputStream input = new ByteArrayInputStream(new byte[0]);
    PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, input, objectMetadata);
    if (null != this.storageClass) {
        putObjectRequest.setStorageClass(this.storageClass);
    }
    try {
        PutObjectResult putObjectResult = (PutObjectResult) callCOSClientWithRetry(putObjectRequest);
        LOG.debug("Store the empty file successfully, cos key: {}, ETag: {}.", key, putObjectResult.getETag());
    } catch (CosServiceException cse) {
        int statusCode = cse.getStatusCode();
        if (statusCode == 409) {
            // 并发上传文件导致,再check一遍文件是否存在
            FileMetadata fileMetadata = this.queryObjectMetadata(key);
            if (null == fileMetadata) {
                // 文件还是不存在,必须要抛出异常
                handleException(cse, key);
            }
            LOG.warn("Upload the file [{}] concurrently.", key);
        } else {
            // 其他错误必须抛出
            handleException(cse, key);
        }
    } catch (Exception e) {
        String errMsg = String.format("Store the empty file failed, cos key: %s, " + "exception: %s", key, e);
        handleException(new Exception(errMsg), key);
    }
}
Also used : CosServiceException(com.qcloud.cos.exception.CosServiceException) ByteArrayInputStream(java.io.ByteArrayInputStream) PutObjectResult(com.qcloud.cos.model.PutObjectResult) ByteArrayInputStream(java.io.ByteArrayInputStream) ResettableFileInputStream(org.apache.hadoop.fs.cosn.ResettableFileInputStream) InputStream(java.io.InputStream) ObjectMetadata(com.qcloud.cos.model.ObjectMetadata) PutObjectRequest(com.qcloud.cos.model.PutObjectRequest) ResponseNotCompleteException(com.qcloud.cos.exception.ResponseNotCompleteException) CosServiceException(com.qcloud.cos.exception.CosServiceException) CosClientException(com.qcloud.cos.exception.CosClientException) IOException(java.io.IOException)

Example 30 with PutObjectRequest

use of com.qcloud.cos.model.PutObjectRequest 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)

Aggregations

PutObjectRequest (com.qcloud.cos.model.PutObjectRequest)45 File (java.io.File)30 PutObjectResult (com.qcloud.cos.model.PutObjectResult)25 CosServiceException (com.qcloud.cos.exception.CosServiceException)17 ObjectMetadata (com.qcloud.cos.model.ObjectMetadata)17 CosClientException (com.qcloud.cos.exception.CosClientException)15 COSClient (com.qcloud.cos.COSClient)13 ClientConfig (com.qcloud.cos.ClientConfig)13 Region (com.qcloud.cos.region.Region)13 BasicCOSCredentials (com.qcloud.cos.auth.BasicCOSCredentials)12 COSCredentials (com.qcloud.cos.auth.COSCredentials)12 Upload (com.qcloud.cos.transfer.Upload)12 GetObjectRequest (com.qcloud.cos.model.GetObjectRequest)10 UploadResult (com.qcloud.cos.model.UploadResult)10 ByteArrayInputStream (java.io.ByteArrayInputStream)8 LinkedList (java.util.LinkedList)8 Test (org.junit.Test)8 CIObject (com.qcloud.cos.model.ciModel.persistence.CIObject)7 CIUploadResult (com.qcloud.cos.model.ciModel.persistence.CIUploadResult)7 PicOperations (com.qcloud.cos.model.ciModel.persistence.PicOperations)7