Using customRequest in Ant design file upload

前端 未结 1 1358
我寻月下人不归
我寻月下人不归 2021-02-11 09:36

I am using Axios to handle the file upload. I am facing a problem showing the upload progress of the file upload. The file upload view I am using is \"picture-card\".

HT

1条回答
  •  南笙
    南笙 (楼主)
    2021-02-11 10:03

    antd Upload uses rc-upload under the hood. onProgress accepts only one argument. I have also used antd Progress for an alternative way of showing progress. Read more about customRequest.

    JSX

    import { Upload, Progress } from "antd";
    
    const App = () => {
      const [defaultFileList, setDefaultFileList] = useState([]);
      const [progress, setProgress] = useState(0);
    
      const uploadImage = async options => {
        const { onSuccess, onError, file, onProgress } = options;
    
        const fmData = new FormData();
        const config = {
          headers: { "content-type": "multipart/form-data" },
          onUploadProgress: event => {
            const percent = Math.floor((event.loaded / event.total) * 100);
            setProgress(percent);
            if (percent === 100) {
              setTimeout(() => setProgress(0), 1000);
            }
            onProgress({ percent: (event.loaded / event.total) * 100 });
          }
        };
        fmData.append("image", file);
        try {
          const res = await axios.post(
            "https://jsonplaceholder.typicode.com/posts",
            fmData,
            config
          );
    
          onSuccess("Ok");
          console.log("server res: ", res);
        } catch (err) {
          console.log("Eroor: ", err);
          const error = new Error("Some error");
          onError({ err });
        }
      };
    
      const handleOnChange = ({ file, fileList, event }) => {
        // console.log(file, fileList, event);
        //Using Hooks to update the state to the current filelist
        setDefaultFileList(fileList);
        //filelist - [{uid: "-1",url:'Some url to image'}]
      };
    
      return (
        
    {defaultFileList.length >= 1 ? null :
    Upload Button
    }
    {progress > 0 ? : null}
    ); };

    Here is a demo

    0 讨论(0)
提交回复
热议问题