How to limit upload file size in express.js

2020-02-29 01:05发布

i got this error says

error:request entity too large 

when uploading a video about 30MB,

here is the setting code

app.use(express.bodyParser({
    uploadDir:'./Temp',
    maxFieldsSize:'2 * 1024 * 1024 * 1024 ',
}));

am not sure how to set the maxFieldsSize property, need some help!!!

6条回答
Ridiculous、
2楼-- · 2020-02-29 01:20
// Comment sart   
// app.use(express.bodyParser({
//    uploadDir:'./Temp',
//    maxFieldsSize:'2 * 1024 * 1024 * 1024 ',
// }));  

// Add this code for maximun 150mb 
app.use(bodyParser.json({limit: '150mb'}));
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
limit: '150mb',
extended: true
})); 

// I did it Okay. Goood luck 
查看更多
唯我独甜
3楼-- · 2020-02-29 01:23

Express uses connect middleware, you can specify the file upload size by using the following

app.use(express.limit('4M'));

Connect Limit middleware

查看更多
太酷不给撩
4楼-- · 2020-02-29 01:33

In 2020 Express uses the body-parser urlencoded function to control the limit. http://expressjs.com/en/4x/api.html#express.urlencoded

These are the default settings inside node_modules>body-parser>lib>types>urlencoded.js https://www.npmjs.com/package/body-parser

  var extended = opts.extended !== false
  var inflate = opts.inflate !== false
  var limit = typeof opts.limit !== 'number'
    ? bytes.parse(opts.limit || '100kb')
    : opts.limit
  var type = opts.type || 'application/x-www-form-urlencoded'
  var verify = opts.verify || false

You can see here that the default setting for limit is 100kb. so in order to up that you can use

app.use(express.urlencoded({ extended: false, limit: '2gb' }));

here are the filetype options available via NPM package bytes ( used by bodyparser ) https://www.npmjs.com/package/bytes

"b" for bytes
"kb" for kilobytes
"mb" for megabytes
"gb" for gigabytes
"tb" for terabytes
"pb" for petabytes

I'm sure this was overkill but I hope this helps the next person.

查看更多
成全新的幸福
5楼-- · 2020-02-29 01:35
var upload = multer({ storage : storage2, limits: { fileSize: 1024 * 1024 * 50 } });

correct format for increasing file uploading size with multer in nodejs

查看更多
爷、活的狠高调
6楼-- · 2020-02-29 01:39

I'm using Express 4. I tried numerous app.use() statements, including the non-deprecated ones listed on this thread, but none of them worked.

Instead, it turned out I only needed to add one line to index.js to change the maxFileSize option in the Formidable module:

// create an incoming form object
var form = new formidable.IncomingForm();

// ADD THIS LINE to increase file size limit to 10 GB; default is 200 MB
form.maxFileSize = 10 * 1024 * 1024 * 1024;

Source: Comments from here.

查看更多
放我归山
7楼-- · 2020-02-29 01:43
app.use(express.limit('4mb'));

But you must make sure you add this line above the below,

app.use(express.bodyParser());

or

app.use(express.json());
app.use(express.urlencoded());

depending on which version you are using.

查看更多
登录 后发表回答