Antd pro 怎么上传图片到阿里云 OSS以及数据的回显
此文章用于记录在日常项目开发中遇到的问题:
一、上传图片到阿里云 OSS 步骤
使用 ProFormUploadButton 组件的 customRequest API 自定义上传方法
1.1 调取服务端提供的接口获取临时访问凭证
const { data: uploadInfo } = await loadUploadInfo();
const client = new OSS({
region: uploadInfo?.region,
accessKeyId: uploadInfo?.keyId || '',
accessKeySecret: uploadInfo?.keySecret || '',
stsToken: uploadInfo?.stsToken,
bucket: uploadInfo?.bucket,
endpoint: 'oss-cn-beijing.aliyuncs.com',
});
1.2 customRequest 自定义上传方法,使用临时访问凭证上传文件
// 封装一个 client.put 方法
const put = async (ossClient: any, path: string, file: File) => {
let ossRes = await ossClient.put(path, file);
let url: string = '';
if (ossRes && ossRes.name) {
url = `https://${ossClient.options.bucket}.${ossClient.options.endpoint.host}/${ossRes.name}`;
} else {
throw new Error('上传失败');
}
return {
url,
};
};
// e 可以获取上传的文件
const path = uploadInfo?.pathPrefix + '/' + e.file.uid.replace(/-/g, '') + '.' + e.file.type.match(/image\/(\w*)/)[1];
// 上传文件到阿里云 oss
put(client, path, e.file).then((res: any) => {
// 将上传成功之后的文件地址返回给 ProFormUploadButton 组件
e.onSuccess(res.url);
}).catch((err) => {
e.onError(err);
});
二、Upload 组件数据回显
const imgs =[{
response: img1Info?.url,
uid: '1',
thumbUrl: img1Info?.url
}];
formRef.current?.setFieldValue('imgs', imgs);
三、遇到的问题
3.1 XHR error(req "error"),PUT(connected: false, keepalive socket: false)
参照官方文档给出的例子使用时,上传文件会报错:
创建 OSS 服务时需要添加 endpoint 字段,endpoint 表示对外服务的访问域名
3.2 ProFormUploadButton 组件不能预览图片
原因:通过浏览器访问存储在OSS中的资源时无法预览而是以附件形式下载。
解决方式:可以自定义预览方法,使用 Image 标签展示图片。
onPreview(file) {
Modal.info({
title: '图片预览',
maskClosable: true,
content: <Image src={file.response} width="100%" preview={false} />,
footer: null
});
},
四、参考
转载自:https://juejin.cn/post/7229520942670004281