How to fix '413 Request Entity Too Large'

2019-06-13 23:34发布

问题:

I am attempting to allow users to upload several images to my website which will then get emailed to all users as attachments but I am coming across an error stating the file size is too large.

I am using Mailgun to send the mail, Cloudinary to upload/store the images, MongoDB as my database, request.js to request the images, Cloud 9 to develop in, and Node.js/Express as my backend.

The user process goes like this:

  • User submits pictures onto the site
  • Pictures are uploaded via Cloudinary and the direct link to each image is saved in the MongoDB database
  • Mail goes out via Mailgun to inform users of the new post with the images added as attachments

I am using request.js to request the images from Cloudinary and then pushing each image into an array which is then added as an attachment parameter for Mailgun.

This works great for smaller images, but when a user uploads a larger batch of high-quality images I receive the error.

I have tried adding a 100MB fileSize limit to Multer, bodyParser.json, and bodyParser.urlencoded as well as a parameterLimit of 100MB.

var upload = multer({ storage: storage, fileFilter: imageFilter, limits: {fileSize: 100000000}});

app.use(bodyParser.json({limit: "100mb", parameterLimit: 100000000}));
app.use(bodyParser.urlencoded({limit: '100mb', extended: true, parameterLimit: 100000000}));

var images = [];
post.images.forEach(function(photo){
    images.push(request(photo));
});

var data =  {
    from: "email <email@email.com>",
    to: "email@email.com",
    subject: 'this is an email',
    html: 'this is an email',
    attachment: images
};

The expected results are a successful email being sent with all of the images attached.

The actual result is this error message:

{ Error: <html>
<head><title>413 Request Entity Too Large</title></head>
<body bgcolor="white">
<center><h1>413 Request Entity Too Large</h1></center>
<hr><center>nginx</center>
</body>
</html>

at IncomingMessage.res.on (/home/ubuntu/workspace/TW/node_modules/mailgun-js/lib/request.js:319:17)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9) statusCode: 413 }

回答1:

It looks like problem here is that you have an Nginx server running in front of your node one, which has a default size limit small. See this question for how to set the size limit: Hardcode header size limit / timeout values in Nginx



回答2:

The problem ended up not being nginx at all, I was trying to email the images as attachments via Mailgun and that has a hard limit of 25MB.

After editing this line in the section where users can upload images everything works perfectly:

let result = await cloudinary.v2.uploader.upload(file.path, {width: 1280, height: 720, crop: "limit"});