Node JS-如何在使用express-fileupload时限制文件大小

Usm*_*bal 4 javascript file-upload node.js

我正在使用express-fileupload,它工作正常并上传图像。我无法找到限制文件大小的方法,也无法编写一个检查来确保上传的文件大小不会超过 1MB。

    app.post('/upload', function(req, res) {
  if (!req.files)
    return res.status(400).send('No files were uploaded.');

  // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
  let sampleFile = req.files.sampleFile;

  // Use the mv() method to place the file somewhere on your server
  sampleFile.mv('/somewhere/on/your/server/filename.jpg', function(err) {
    if (err)
      return res.status(500).send(err);

    res.send('File uploaded!');
  });
});
Run Code Online (Sandbox Code Playgroud)

我尝试了类似的方法,它实际上剪切了剩余的图像

    app.use(fileUpload({
    limits: {
        fileSize: 1000000 //1mb
    },
}));
Run Code Online (Sandbox Code Playgroud)

我可以通过检查每个文件的文件大小来执行此 JavaScript,但是没有任何内置功能吗???单击一次即可上传多个文件怎么样?对于多个文件,它将遍历循环并检查每个文件的大小,并排除那些大小大于 1mb 的文件,并仅上传那些大小符合要求的文件。所以我想知道除了编写自己的代码之外,是否没有任何内置功能???

Cla*_*lim 6

它会截断剩余图像,因为已达到大小限制,并且您没有明确设置中间件以在这种情况下中止上传。

因此,尝试将选项“abortOnLimit”设置为 true,如下所示:

 app.use(fileUpload({
    limits: {
        fileSize: 1000000 //1mb
    },
    abortOnLimit: true
 }));
Run Code Online (Sandbox Code Playgroud)

有关更多信息,这是文档讲述的有关使用选项“abortOnLimit”的内容:

如果为 true,则当文件大于大小限制时返回 HTTP 413。否则,它将在生成的文件结构中添加 truncate = true。

源码链接: https: //www.npmjs.com/package/express-fileupload