【问题标题】:Display progress upload for multiple files with Axios and React使用 Axios 和 React 显示多个文件的上传进度
【发布时间】:2021-05-04 21:11:26
【问题描述】:

我正在尝试在我的 React 应用中显示文件上传的进度。

首先,我创建了这个函数来上传多个文件:

  const [files, setFiles] = useState([])
  const saveDocuments = () => {
    try {
      files.forEach((file) => {
        axios.post("/api/documents", formData, {
          let formData = new FormData();
          formData.append("attached_file", file);
          formData.append("name", file.name);
          headers: {
            "X-CSRFTOKEN": getCookie("csrftoken"),
            "Content-Type": "multipart/form-data",
          },
          onUploadProgress: (progressEvent) => {
            const percentCompleted = Math.round(
              (progressEvent.loaded * 100) / progressEvent.total
            );
            file.progress = percentCompleted;
            console.log(percentCompleted);
          },
        });
      });
    } catch (e) {
      console.log(e);
    }
  };

使用此代码,我可以在控制台中看到 percentCompleted 值。

在我的渲染函数中,我试图显示这个进度值:

return(
  <ul>
    {files.map((file, index) => (
      <li key={index} >
        <div>{file.name}</div>
        <div>{file.progress} %</div>
      </li>
    ))}
  </ul>;  
)

进度值不显示;但是 react 开发工具会显示状态中的进度值。

我想我没有正确更新file 对象的状态。我该如何处理?感谢您的帮助。

【问题讨论】:

  • 您没有在 saveDocuments 中设置任何状态。
  • files 是我的状态数组(我已上传代码以表明这一点)。
  • 看起来您并没有在任何地方更新文件状态。您需要在某处调用 setFiles 函数才能真正更新状态。
  • 我已经解决了这个问题,我会尽快发布我的解决方案

标签: reactjs axios


【解决方案1】:

所以我找到了解决方案,我必须使用新键 progress 创建数组 files 的副本,其值为 percentCompleted

const saveDocuments = () => {
    try {
      files.forEach((file) => {

        axios.post("/api/documents", formData, {
          let formData = new FormData();
          formData.append("attached_file", file);
          formData.append("name", file.name);
          headers: {
            "X-CSRFTOKEN": getCookie("csrftoken"),
            "Content-Type": "multipart/form-data",
          },
          onUploadProgress: (progressEvent) => {
            const percentCompleted = Math.round(
              (progressEvent.loaded * 100) / progressEvent.total
            );
            // Create copy of file
            let newFile = file;
            // ... and set the progress
            newFile.progress = percentCompleted;
            // Create copy of files array
            let filesCopy = [...files];
            // Find the index of the file object
            let fileIndex = filesCopy.findIndex((el) => el.name === file.name);
            //... and replace the object with the new one containing the [progress] key
            filesCopy[fileIndex] = newFile;
            // Finally, update the state
            setFilesUploaded([...filesCopy]);
            file.progress = percentCompleted;
          },
        });
      });
    } catch (e) {
      console.log(e);
    }
  };

然后,渲染函数返回包含带有progress 键的对象的新数组:

return(
  <ul>
    {filesUploaded.map((file, index) => (
      <li key={index} >
        <div>{file.name}</div>
        <div>{file.progress} %</div>
      </li>
    ))}
  </ul>;  
)

【讨论】:

    猜你喜欢
    • 2017-12-07
    • 2018-01-19
    • 2020-02-11
    • 2015-10-21
    • 2020-04-09
    • 1970-01-01
    • 2014-02-25
    • 2014-06-06
    相关资源
    最近更新 更多