There are many articles, tutorials, and questions about file uploads in node but mostly they are for beginners and none of them fully explains how to secure file uploads for production.
I have tried very hard to find a complete answer on how to do it, but it was not successful.
Below is an explanation of my findings.
Limit file size on uploads:
Limit file uploads to only certain routes:
I can’t get this to actually work but here is what I have tried:
and add the multipart middleware to every upload route:
app.post('/upload', express.multipart(), uploadController.uploadPhoto);
This part doesn’t work, but the upload works fine if I leave
express.bodyParser(). So what am I doing wrong?
Checking uploaded file type before saving upload to disk:
I couldn’t figure this part out, but a suggestion was to write a custom middleware that uses formidable to parse file uploads and trying to resize the file before it is saved (assuming that it is an image) using a library like image magic. The suggestion was that this would make the image safe and ensure that it is actually an image (because the process would fail if it is not an image).
This would only work with images though, so it is not a complete solution.
How can I implement this? Any example code?
Is there anything else that I am missing for uploads to be safe?