Multer | Stop file upload

流过昼夜 提交于 2019-12-04 17:14:04
LorenzoGi

According to Multer documentation: (https://www.npmjs.org/package/multer) you could use onFileUploadStart(file), and return false if the size is above your limit.

For example:

var express = require('express');
var multer  = require('multer');

var maxSize = 32 * 1000 * 1000;

var app = express();
app.use(multer({
  dest: './uploads/',
  onFileUploadStart: function(file, req, res){
    if(req.files.file.length > maxSize) {
      return false;
    }
  })
}));

Try multer limits–

app.use('/userimage', multer({
  limits: { fileSize: 1* 1024 * 1024}, //1mb
  onFileUploadStart: function (file, req, res) {
    console.log(file.fieldname + ' fileupload is starting ...');
  }}));

Documentation here https://www.npmjs.org/package/multer

That´s how I'm dealing with this problem in my project. It seems the best solution for now.

api.js

var multer = require('./config/multer')();
var utils = require('./utils');

module.exports = function(app, dao) {
  app.post('/docs/:system', multer, function(req, res) {
    var file = req.files.documento;
    if (file.truncated) {
      utils.removeFile(file.path); // remove the truncated file
      return res.status(413).end(); // 413 ("Request Entity Too Large")
    }
    ...
    res.status(200).send({_id : document._id});
  }); ...

config/multer.js

var multer = require('multer');
var config = require('./config')();

module.exports = function() {

    return multer({ dest: config.BASE_UPLOAD_FOLDER, limits: {fileSize: config.MAX_FILE_SIZE_FOR_UPLOAD},
      ...
      onFileSizeLimit: function (file) {
        console.log('> The file size exceeds the maximum size allowed (' + config.MAX_FILE_SIZE_FOR_UPLOAD/(1024*1024) + 'MB)');
      },
      onFileUploadComplete: function(file) {
        console.log('> File \'' + file.fieldname + '\' stored in \'' + file.path + '\'' + (file.truncated ? ' (TRUNCATED).' : '.') );
      }
    });

};

utils.js

var fs = require('fs');

var removeFile = function (filePath) {
  try {
    fs.unlink(filePath);
    console.log('File"' + filePath + '" removed!');     
  } catch (err) {
    ...
  }
};
...

exports.removeFile = removeFile;

I think the best place to do this file size checking is on frontend instead of backend. When user selects a file to upload, we can get file size immediately, and alert user if the size exceeds allowed limit.

Here's how I do it:

$('#upload input').change(function(click) {
  var file = this.files[0];
  if (file.size > MAX_FILE_SIZE_MB * 1024 * 1024) {
    alert('Sorry, selected file exceeds allowed size limit (' + MAX_FILE_SIZE_MB + 'MB).');
    return false;
  }

  // Post file upload request via AJAX
  // ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!