Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node express upload file with mean stack

I should implement an upload form I thought of using bodyparser but I read http://andrewkelley.me/post/do-not-use-bodyparser-with-express-js.html

so what's the way to upload a file with express using the mean stack ? may be formidable or other modules ?

like image 663
Whisher Avatar asked Jan 17 '14 10:01

Whisher


People also ask

How do I upload files using Express?

Open the local page http://127.0.0.1:2000/ to upload the images. Select an image to upload and click on "Upload Image" button. Here, you see that file is uploaded successfully. You can see the uploaded file in the "Uploads" folder.


2 Answers

That warning is specifically against adding the express.bodyparser middleware to your entire stack as it adds express.multipart to all POST endpoints and therefore file uploads are automatically accepted at all POST endpoints. By default the framework automatically saves any uploaded files to /tmp and so unless you are cleaning them up an attacker could flood your disk with uploaded files.

If you want to avoid using additional modules, what you should do is implement express.multipart on the endpoint(s) where you want to allow file uploads. Here's what I'm talking about:

var express = require("express")
  , app = express();

// middleware (no bodyparser here)
app.use(express.json());
app.use(express.urlencoded());

// average GET endpoint
app.get("/", function(req,res) {
  res.send('ok');
});

// average POST endpont
app.post("/login", function(req,res) {
  res.send('ok');
});

// File upload POST endpoint
app.post('/upload', express.multipart, function(req, res) {
  //File upload logic here
  //Make sure to delete or move the file accordingly here, otherwise files will pile up in `/tmp`
});

Note the inclusion of express.multipart in the file upload endpoint. This endpoint will now process multipart file uploads, and assuming you handle them correctly they won't be a threat.

Now, having told you all of this, Connect is moving to deprecate multipart due to this exact issue, but there don't seem to be any plans to add a stream based file upload replacement. What they instead recommend is that you use node-multiparty which uses streams to avoid ever placing a file on disk. However, there don't seem to be any good references I can find for using multiparty as a middleware without saving files though, so you'll have to contact the author of multiparty or take a closer look at the API for implementing it with Express.

like image 134
Rob Riddle Avatar answered Oct 25 '22 10:10

Rob Riddle


I created an example that uses Express & Multer - very simple, avoids all Connect warnings

https://github.com/jonjenkins/express-upload

like image 42
Jon J Avatar answered Oct 25 '22 11:10

Jon J