/* eslint no-console:0 */
import React from 'react';
import axios from 'axios';
import { Upload } from 'antd';
const uploadProps = {
action: '/upload.do', // 接口
multiple: false, // 是否支持多选文件 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;