首页 > 解决方案 > 如何在 NodeJS/Express 的前端持续更新文件上传的进度

问题描述

我在 EJS 前端有一个用于多文件上传的表单,我正在寻找一种更新 id 为“progressSpan”的跨度的方法,以显示正在上传的文件的当前进度百分比。

前端表单如下所示:

<form method="POST" action="/upload" enctype="multipart/form-data" id="uploadForm">
      <label>Select Files</label>
      <input type="file" name="fileUpload" id="realFileinput" multiple>
      <button type="submit" id="submit-upload-btn" class="uploadFormBtns">Start Uploading</button>
      <span id="progressSpan>0%</span>
</form>

负责处理后端上传的函数是使用 multer 编写的,尽管如果 express-fileupload 之类的东西更适合进度跟踪,那么更改它就没什么大不了的。在下面的代码片段中,fileData 是一个 JSON 对象数组,其中包含一个名称和一个文件大小,在这种情况下由前端中的一个无关函数处理。根据结果​​(成功/错误),它会打印带有相应消息的 index.ejs 文件

router.post('/upload', (req, res) => {


upload(req, res, (err) => {
if (err) {
  //render error
  res.render('index', { msg: err, fileData });

} else {

    req.files.forEach(file => {
      
      fileData.push({
        name: file.filename,
        fileSize: convertDataUnit(dir, file.filename)
      });
    });
    res.render("index", { msg: "Upload successful!", fileData });
   }
 });
});

标签: javascriptnode.jsexpressmulter

解决方案


推荐阅读