react 客户端直传 腾讯云 COS

本文最后更新于 2024年4月11日 上午

安装 COS 依赖模块

1
npm i cos-js-sdk-v5 --save

上传逻辑

  • 初始化

    1
    2
    3
    const [tencentClient, setTencentClient] = useState<any>(null) /// 腾讯云云OSS实例
    const [percent, setPercent] = useState<any>(0) /// 上传进度条
    const [flag, setFlag] = useState<boolean>(false)
  • 实例化

    1
    2
    3
    4
    5
    const client = new COS({
    SecretId: data.secretId, /// SecretId
    SecretKey: data.secretKey /// secretKey
    })
    setTencentClient(client)
  • 上传逻辑

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    // 腾讯云上传文件 - 方法
    const TencentCosUploadFn = async (url: string, file: any, onSuccess: (uploadResult: any, file: any) => void, onError: (error: any) => void) => {
    try {
    const uploadResult = await tencentClient.putObject({
    Bucket: `${tencentConfig.bucket}-${tencentConfig.appid}` /* 存储桶 */,
    Region: tencentConfig.region /* 存储桶所在地域,必须字段 */,
    Key: url /* 文件名 */,
    StorageClass: 'STANDARD', // 上传模式, 标准模式
    Body: file, // 上传文件对象
    onProgress: function (p: any) {
    // console.log('获取进度条的值==>', )
    let perNum: any = (p * 100).toFixed(2)
    if (perNum > 0) {
    setFlag(true)
    }
    if (perNum == 100) {
    setFlag(false)
    }
    setPercent(Number(perNum))
    // console.log("[cos.postObject-seccess]", JSON.stringify(info));
    }
    })
    // path https://upload-go-1257815509.cos.ap-shanghai.myqcloud.com/WX20240311-191010%402x.png
    // https://upload-go-1257815509.cos.ap-shanghai.myqcloud.com/app/ip-rc-upload-1710236957380-3.png
    const path = 'https://' + `${tencentConfig.bucket}-${tencentConfig.appid}.` + 'cos.' + tencentConfig.region + '.' + 'myqcloud.com/' + url
    // console.log('uploadResult', path)
    await saveUploadUrl(path)
    onSuccess(uploadResult, file)
    } catch (err) {
    onError(err)
    }
    }

  • 自定义上传

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    // 自定义上传
    const uploadProps: UploadProps = {
    beforeUpload: beforeUpload,
    showUploadList: false,
    customRequest: OssUpload,
    listType: 'picture-card',
    onChange(info) {
    // console.log('onChange😊===>', info)
    if (info.file.status !== 'uploading') {
    // console.log(info.file, info.fileList)
    }
    if (info.file.status === 'done') {
    // console.log(`${info.file.name} 文件上传成功`)
    message.success(`${info.file.name} 文件上传成功`)
    } else if (info.file.status === 'error') {
    info.fileList = info.fileList.filter((item) => item.uid !== info.file.uid)
    message.error(`${info.file.name} 文件上传失败`)
    }
    }
    }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<Space direction='vertical' style={{ display: 'flex' }}>
<div className='uploadTitleBox'>{getUploadTitle()}</div>
<Dragger {...uploadProps}>
<p className='ant-upload-drag-icon'>
<CloudUploadOutlined />
</p>
<p className='ant-upload-text'>将文件拖拽至此,或者点击上传</p>
</Dragger>
{flag && (
<Space.Compact block>
<Progress style={{ color: '#fff' }} percent={percent} />
</Space.Compact>
)}
</Space>

效果图


react 客户端直传 腾讯云 COS
https://dev.dgdream.online/2024/04/06/react 客户端直传 腾讯云 COS/
作者
执念
发布于
2024年4月6日
更新于
2024年4月11日
许可协议