Multer | Stop file upload

2019-04-13 11:51发布

问题:

I am using expressjs 4.0 along with multer to handle file uploads.

Problem is, I want to stop file upload when the file's size exceeds a maxSize variable. But multer uploads file anyways.

Is there a way to stop this behaviour.

Some example code :

app.post('/upload', function(req, res) {

    var maxSize = 32 * 1000 * 1000 // 32mb max

    if(req.files.file.length > maxSize) {
        // stop upload
    } else {
        // continue
        res.send(201);
    }
});

回答1:

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;
    }
  })
}));


回答2:

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



回答3:

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;


回答4:

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
  // ...
}