腾讯云cos上传及获取

需求背景:在开发过程中遇到过需要用户上传文件及下载文件的需求,可文件上传到服务器又会对服务器造成越来越大的压力,这时就考虑把文件放到云上。(这里的云不是天上的云哈~~~

前期准备:开通腾讯云账号并购买cos。

                  需准备:cosAPPID,secretID,secretKey,cosBucket(腾讯云内创建)

获取BUCKET代码

/**
     * 获取bucket
     * @param unionId
     * @param hospitalId
     * @return
     */
    private String getBucket (String unionId,String hospitalId){
        //这个我是在数据库里配置的,也可以在配置文件内配置,通个账号也可以写死。
        String cosAppid = xxx.getConfigValue(unionId, hospitalId,
                HospitalConfigTypeEnumeration.COS_APPID).getValueData();
        String cosBucket =xxx.getConfigValue(unionId, hospitalId,
                HospitalConfigTypeEnumeration.COS_BUCKET).getValueData();
        return cosBucket+"-"+cosAppid;
    }

获取cos服务

  /**
     * 获取cos服务
     * @param unionId
     * @param hospitalId
     * @return
     */
    private COSClient getCOSClient(String unionId,String hospitalId){
        //获取cosSecretID 可以写死,也可以配置,按自己需求
        String cosSecretId =xxx.getConfigValue(unionId, hospitalId,
                HospitalConfigTypeEnumeration.COS_SECRETID).getValueData();
        String cosSecretKey = xxx.getConfigValue(unionId, hospitalId,
                HospitalConfigTypeEnumeration.COS_SECRETKEY).getValueData();
        COSCredentials cred = new BasicCOSCredentials(cosSecretId, cosSecretKey);
        //cos 服务器
        Region region = new Region("ap-shanghai");
        ClientConfig clientConfig = new ClientConfig(region);
        // 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }

验证文件类型是否符合要求(工具)

/**
     * 验证文件类型是否符合要求
     *
     * @param ext
     * @return
     * @Description
     */
    public static boolean isValidFileExt(String ext) {
        ext = ext.toLowerCase(Locale.ENGLISH);
        for (String s : FILE_EXT) {
            if (s.equalsIgnoreCase(ext)) {
                return true;
            }
        }
        return false;
    }

上传代码 

 /**
     *  文件上传
     * @param file 文件
     * @param path 文件名称
     * @return 文件地址
     * @throws IOException
     */
    public String upLoadCos(InputStream file, String path,String unionId,String hospitalId)throws IOException {
        //涉及到的地方比较多,建议写个公共模块。
        //下面会po出获取桶和cos服务器代码
        String bucket = getBucket(unionId, hospitalId);
        COSClient cosClient = getCOSClient(unionId, hospitalId);
        // 指定要上传到 COS 上对象键
        String ext = FilenameUtils.getExtension(path);
        if(!isValidFileExt(ext)){
            throw new ServiceException("文件类型不支持!");
        }
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(file.available());
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, path, file,objectMetadata);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        return "https://"+putObjectRequest.getBucketName()+".cos.ap-shanghai.myqcloud.com/"+path;
    }

 上传文件之后就会获取到一串cos的URL:bucketName+cos服务器+文件名

https://wjytest-1251304050.cos.ap-shanghai.myqcloud.com/457cf133da90c99e121fc4615a6fce13.jpg

不过这个时候打开你会发现是看不到的,这是因为cos进行加密了。这个时候就用到了下面这个获取私有读权限来获取文件了。

获取请求预签名:

 /**
     * 获取请求预签名 URL
     * @param unionId
     * @param hospitalId
     * @return
     * @throws CosClientException
     */
    public URL generatePresignedUrl(String unionId,String hospitalId,String picUrl)throws CosClientException{
        String bucket = getBucket(unionId, hospitalId);
        GeneratePresignedUrlRequest req =
                new GeneratePresignedUrlRequest(bucket, picUrl, HttpMethodName.GET);
        // 设置签名过期时间(可选), 若未进行设置, 则默认使用 ClientConfig 中的签名过期时间(1小时)
        // 这里设置签名在半个小时后过期
        Date expirationDate = new Date(System.currentTimeMillis() + 30L * 60L * 1000L);
        req.setExpiration(expirationDate);
        COSClient cosClient = getCOSClient(unionId, hospitalId);
        URL url = cosClient.generatePresignedUrl(req);
        log.info(url.toString());
        cosClient.shutdown();
        return url;
    }

然后通过这个接口获取到的URL就可以打开上传的文件了!

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你好!要在Python中使用腾讯云COS(对象存储)服务进行上传,你可以按照以下步骤进行操作: 1. 首先,确保你已经在腾讯云上创建了COS存储桶,并获取了访问密钥(SecretId和SecretKey)。 2. 安装腾讯云COS SDK。你可以使用以下命令来安装cos-python-sdk-v5: ``` pip install -U cos-python-sdk-v5 ``` 3. 在你的Python代码中导入COS SDK并进行配置: ```python import os from qcloud_cos import CosConfig from qcloud_cos import CosS3Client # 配置腾讯云COS secret_id = 'your_secret_id' secret_key = 'your_secret_key' region = 'your_bucket_region' # 存储桶所在地域,例如:ap-guangzhou token = None # 若使用临时密钥需要传入 Token,默认为空,可不填 scheme = 'https' # 使用 https 协议 # 配置 COS SDK config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme) client = CosS3Client(config) ``` 请将上述代码中的 `your_secret_id`、`your_secret_key` 和 `your_bucket_region` 替换为你的实际信息。 4. 使用以下代码将文件上传COS中的指定存储桶: ```python # 上传文件 bucket = 'your_bucket_name' # 存储桶名称 local_file = 'path/to/local/file' # 本地文件路径 cos_file = 'path/to/cos/file' # COS文件路径 with open(local_file, 'rb') as fp: response = client.put_object( Bucket=bucket, Body=fp, Key=cos_file, StorageClass='STANDARD', EnableMD5=False ) ``` 请将上述代码中的 `your_bucket_name`、`path/to/local/file` 和 `path/to/cos/file` 替换为你的实际信息。 这样,你就可以使用Python代码将文件上传腾讯云COS了。记得适当处理异常和错误情况,以确保上传操作的可靠性和安全性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值