解决antd upload自定义上传customRequest,上传时一直loading加载的问题
antd自定义上传customRequest时,无法正常显示上传成功状态,一直在上传的loading状态中。antd官方API中自定义上传参数customRequest介绍:调用onSuccess解决问题:代码事例:customRequest = (options)=>{console.log(options);let params = ne...
·
antd自定义上传customRequest时,无法正常显示上传成功状态,一直在上传的loading状态中。
antd官方API中自定义上传参数customRequest介绍:
调用onSuccess解决问题:
代码事例:
customRequest = (options)=>{
console.log(options);
let params = new FormData();
params.append("file", options.file);
this.props.ajax.post(`/admin/sys-file/upload`, params, {headers: {'Content-Type': 'multipart/form-data'}}).then((res)=>{
options.onSuccess(res, options.file);
})
}
分析:
查看参数options的详细信息:
可以发现onProgress事件与onSuccess事件,onProgress是上传进度相关的,onSuccess是上传成功监听事件。
- 设置进度条相关监听,解决进度条显示不正常的问题:
onUploadProgress: ({ total, loaded }) => {
onProgress({ percent: Math.round(loaded / total * 100).toFixed(2) }, file);
}
- 调用onSuccess事件,解决loading一直加载的问题:
onSuccess(response, file);
贴一下参考demo:
以下是customRequest的参考demo代码
/* eslint no-console:0 */
import React from 'react';
import axios from 'axios';
import Upload from 'rc-upload';
const uploadProps = {
action: '/upload.do',
multiple: false,
data: { a: 1, b: 2 },
headers: {
Authorization: '$prefix $token',
},
onStart(file) {
console.log('onStart', file, file.name);
},
onSuccess(res, file) {
console.log('onSuccess', res, file.name);
},
onError(err) {
console.log('onError', err);
},
onProgress({ percent }, file) {
console.log('onProgress', `${percent}%`, file.name);
},
customRequest({
action,
data,
file,
filename,
headers,
onError,
onProgress,
onSuccess,
withCredentials,
}) {
// EXAMPLE: post form-data with 'axios'
// eslint-disable-next-line no-undef
const formData = new FormData();
if (data) {
Object.keys(data).forEach(key => {
formData.append(key, data[key]);
});
}
formData.append(filename, file);
axios
.post(action, formData, {
withCredentials,
headers,
onUploadProgress: ({ total, loaded }) => {
onProgress({ percent: Math.round((loaded / total) * 100).toFixed(2) }, file);
},
})
.then(({ data: response }) => {
onSuccess(response, file);
})
.catch(onError);
return {
abort() {
console.log('upload progress is aborted.');
},
};
},
};
const Test = () => {
return (
<div
style={{
margin: 100,
}}
>
<div>
<Upload {...uploadProps}>
<button type="button">开始上传</button>
</Upload>
</div>
</div>
);
};
export default Test;
欢迎访问本文的个人博客链接: https://br-bai.github.io/2020/03/12/解决Ant Design使用Upload自定义上传customRequest,上传时一直loading加载的问题
更多推荐
已为社区贡献1条内容
所有评论(0)