react 客户端直传 阿里云OSS

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

安装 OSS 依赖模块

1
npm i ali-oss --save

上传逻辑

  • 初始化 State

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

    1
    2
    3
    4
    5
    6
    7
    const client = new OSS({
    region: data.region, /// 地区
    accessKeyId: data.accessKeyId, // accessKeyId
    accessKeySecret: data.accessKeySecret, // accessKeySecret
    bucket: data.bucket /// bucket 桶
    })
    setClient(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
    // 阿里云上传文件 - 方法
    const AliyunOssUploadFn = async (url: string, file: any, onSuccess: (uploadResult: any, file: any) => void, onError: (error: any) => void) => {
    try {
    const uploadResult = await client.multipartUpload(url, file, {
    progress: function (p: number) {
    // console.log('获取进度条的值==>', (p * 100).toFixed(2))
    let perNum: any = (p * 100).toFixed(2)
    if (perNum > 0) {
    setFlag(true)
    }
    if (perNum == 100) {
    setFlag(false)
    }
    setPercent(Number(perNum))
    }
    })
    // 拼接图片路径
    // https://upload-go.oss-cn-hangzhou.aliyuncs.com/temp/WX20240311-191010%402x-rc-upload-1710156464135-3.png
    // https://upload-go.
    const path = 'https://upload-go.' + aliyunConfig.region + '.aliyuncs.com/' + url
    await saveUploadUrl(path)
    // console.log('上传图片===>>>', uploadResult, url, path)
    onSuccess(uploadResult, file)
    } catch (err) {
    // console.log('上传异常', err)
    onError(err)
    }
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 自定义上传
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 客户端直传 阿里云OSS
https://dev.dgdream.online/2024/04/06/react 客户端直传 阿里云OSS/
作者
执念
发布于
2024年4月6日
更新于
2024年4月11日
许可协议