1. /* eslint no-console:0 */
    2. import React from 'react';
    3. import axios from 'axios';
    4. import { Upload } from 'antd';
    5. const uploadProps = {
    6. action: '/upload.do', // 接口
    7. multiple: false, // 是否支持多选文件 false为不支持
    8. data: { a: 1, b: 2 }, // 上传的额外参数
    9. headers: { // 请求头
    10. Authorization: '$prefix $token',
    11. },
    12. onStart(file) { // 开始上传
    13. console.log('onStart', file, file.name);
    14. },
    15. onSuccess(res, file) { // 上传成功
    16. console.log('onSuccess', res, file.name);
    17. },
    18. onError(err) { // 上传失败
    19. console.log('onError', err);
    20. },
    21. onProgress({ percent }, file) { // 监听上传进度
    22. console.log('onProgress', `${percent}%`, file.name);
    23. },
    24. customRequest({ // 自定义上传,覆盖默认
    25. action,
    26. data,
    27. file,
    28. filename,
    29. headers,
    30. onError,
    31. onProgress,
    32. onSuccess,
    33. withCredentials,
    34. }) {
    35. // EXAMPLE: post form-data with 'axios'
    36. // eslint-disable-next-line no-undef
    37. const formData = new FormData();
    38. if (data) {
    39. Object.keys(data).forEach((key) => {
    40. formData.append(key, data[key]);
    41. });
    42. }
    43. formData.append(filename, file);
    44. axios
    45. .post(action, formData, {
    46. withCredentials,
    47. headers,
    48. onUploadProgress: ({ total, loaded }) => {
    49. onProgress({ percent: Math.round((loaded / total) * 100).toFixed(2) }, file);
    50. },
    51. })
    52. .then(({ data: response }) => {
    53. onSuccess(response, file);
    54. })
    55. .catch(onError);
    56. return {
    57. abort() {
    58. console.log('upload progress is aborted.');
    59. },
    60. };
    61. },
    62. };
    63. const Test = () => {
    64. return (
    65. <div
    66. style={{
    67. margin: 100,
    68. }}
    69. >
    70. <div>
    71. <Upload {...uploadProps}>
    72. <button type="button">开始上传</button>
    73. </Upload>
    74. </div>
    75. </div>
    76. );
    77. };
    78. export default Test;