react 客户端直传 阿里云OSS
本文最后更新于 2024年4月11日 上午
安装 OSS
依赖模块
1 |
|
上传逻辑
初始化
State
1
2
3const [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
7const 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 |
|
1 |
|
效果图
react 客户端直传 阿里云OSS
https://dev.dgdream.online/react 客户端直传 阿里云OSS/