Search in sources :

Example 56 with ClientConfig

use of com.qcloud.cos.ClientConfig in project halo by ruibaby.

the class TencentCosFileHandler method delete.

@Override
public void delete(String key) {
    Assert.notNull(key, "File key must not be blank");
    // Get config
    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();
    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);
    try {
        cosClient.deleteObject(bucketName, key);
    } catch (Exception e) {
        throw new FileOperationException("附件 " + key + " 从腾讯云删除失败", e);
    } finally {
        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) FileOperationException(run.halo.app.exception.FileOperationException) Region(com.qcloud.cos.region.Region) ClientConfig(com.qcloud.cos.ClientConfig) FileOperationException(run.halo.app.exception.FileOperationException)

Example 57 with ClientConfig

use of com.qcloud.cos.ClientConfig 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 58 with ClientConfig

use of com.qcloud.cos.ClientConfig 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 59 with ClientConfig

use of com.qcloud.cos.ClientConfig in project xian by happyyangyuan.

the class CosFileWriter method main.

public static void main(String[] args) {
    COSClient cosClient = new COSClient(10053621, "AKID5iJcsYewRYIJhqQsoaLQ7Ks1XIO6eYPs", "Gm0nqHOPzUG1MRRJnBLX4UwwQMoh8v4y");
    ClientConfig config = new ClientConfig();
    config.setRegion("sh");
    cosClient.setConfig(config);
    UploadFileRequest request = new UploadFileRequest("xian", "/xian_runtime_IDE_happyyangyuan/xian/yy/991.txt", "测试data".getBytes());
    request.setInsertOnly(InsertOnly.OVER_WRITE);
    String uploadFileRet = cosClient.uploadFile(request);
    LOG.info("上传文件返回:" + uploadFileRet);
    GetFileInputStreamRequest inputStreamRequest = new GetFileInputStreamRequest("xian", "/xian_runtime_IDE_happyyangyuan/xian/yy/991.txt");
    inputStreamRequest.setUseCDN(false);
    try (InputStream inputStream = cosClient.getFileInputStream(inputStreamRequest)) {
        System.out.println("读文件:" + StringIO.readFully(inputStream));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : COSClient(com.qcloud.cos.COSClient) UploadFileRequest(com.qcloud.cos.request.UploadFileRequest) InputStream(java.io.InputStream) ClientConfig(com.qcloud.cos.ClientConfig) GetFileInputStreamRequest(com.qcloud.cos.request.GetFileInputStreamRequest)

Example 60 with ClientConfig

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

Aggregations

ClientConfig (com.qcloud.cos.ClientConfig)107 COSClient (com.qcloud.cos.COSClient)103 Region (com.qcloud.cos.region.Region)103 COSCredentials (com.qcloud.cos.auth.COSCredentials)99 BasicCOSCredentials (com.qcloud.cos.auth.BasicCOSCredentials)96 CosClientException (com.qcloud.cos.exception.CosClientException)40 CosServiceException (com.qcloud.cos.exception.CosServiceException)38 File (java.io.File)22 ObjectMetadata (com.qcloud.cos.model.ObjectMetadata)14 PutObjectResult (com.qcloud.cos.model.PutObjectResult)14 PutObjectRequest (com.qcloud.cos.model.PutObjectRequest)13 TransferManager (com.qcloud.cos.transfer.TransferManager)13 ExecutorService (java.util.concurrent.ExecutorService)13 AnonymousCOSCredentials (com.qcloud.cos.auth.AnonymousCOSCredentials)7 CopyObjectRequest (com.qcloud.cos.model.CopyObjectRequest)7 LinkedList (java.util.LinkedList)7 GetObjectRequest (com.qcloud.cos.model.GetObjectRequest)6 FileOperationException (run.halo.app.exception.FileOperationException)6 IOException (java.io.IOException)5 CopyResult (com.qcloud.cos.model.CopyResult)4