Tencent COS Uploader
Overview
Use Tencent COS Python SDK to upload a local file and return presigned URLs for browser preview and file download.
Prerequisites
- 1. Install dependency:
CODEBLOCK0
- 2. Prepare COS credentials (env vars preferred):
- - INLINECODE0
- INLINECODE1
- INLINECODE2
- INLINECODE3
- INLINECODE4 (optional, for temporary credentials)
Workflow
- 1. Confirm required inputs:
-
region (from
--region or env)
-
bucket (from
--bucket or env)
-
--file local file path
-
--key object key in bucket (default is filename)
- 2. Run the script:
CODEBLOCK1
- 3. Return JSON output containing:
-
view_url: GET presigned URL for viewing
-
download_url: presigned URL with
attachment disposition
-
upload_result: SDK upload response
Script Parameters
- -
--region COS region, optional if COS_REGION exists - INLINECODE17 bucket name with appid suffix, optional if
COS_BUCKET exists - INLINECODE19 local file path to upload, required
- INLINECODE20 object key in bucket, optional
- INLINECODE21 URL expiration seconds, default INLINECODE22
- INLINECODE23 optional if
COS_SECRET_ID exists - INLINECODE25 optional if
COS_SECRET_KEY exists - INLINECODE27 optional if
COS_SESSION_TOKEN exists - INLINECODE29
https or http, default INLINECODE32 - INLINECODE33 custom filename for download prompt (optional)
Notes
- - Keep
expires as short as practical to reduce link leakage risk. - INLINECODE35 is generated via
get_presigned_download_url; view_url is generated via get_presigned_url(Method='GET'). - If
--key is omitted, the script uses the source filename as object key.
Tencent COS 上传器
概述
使用腾讯云COS Python SDK上传本地文件,并返回用于浏览器预览和文件下载的预签名URL。
前置条件
- 1. 安装依赖:
bash
pip install cos-python-sdk-v5
- 2. 准备COS凭证(推荐使用环境变量):
- - COSSECRETID
- COSSECRETKEY
- COSREGION
- COSBUCKET
- COSSESSIONTOKEN(可选,用于临时凭证)
工作流程
- 1. 确认所需输入:
- region(来自--region或环境变量)
- bucket(来自--bucket或环境变量)
- --file 本地文件路径
- --key 存储桶中的对象键(默认为文件名)
- 2. 运行脚本:
bash
python3 scripts/cosuploadand_presign.py \
--region ap-guangzhou \
--bucket my-bucket-1250000000 \
--file /absolute/path/to/file.pdf \
--key reports/2026/file.pdf \
--expires 3600
- 3. 返回JSON输出,包含:
- view_url:用于预览的GET预签名URL
- download_url:带有attachment内容配置的预签名URL
- upload_result:SDK上传响应
脚本参数
- - --region COS区域,如果存在COSREGION则可选
- --bucket 带appid后缀的存储桶名称,如果存在COSBUCKET则可选
- --file 要上传的本地文件路径,必填
- --key 存储桶中的对象键,可选
- --expires URL过期秒数,默认3600
- --secret-id 如果存在COSSECRETID则可选
- --secret-key 如果存在COSSECRETKEY则可选
- --session-token 如果存在COSSESSIONTOKEN则可选
- --scheme https或http,默认https
- --download-filename 下载提示的自定义文件名(可选)
注意事项
- - 尽量保持expires时间较短,以降低链接泄露风险。
- downloadurl通过getpresigneddownloadurl生成;viewurl通过getpresigned_url(Method=GET)生成。
- 如果省略--key,脚本将使用源文件名作为对象键。