File Uploads in Node.js

We will use Express Framework  and middleware called “multer”.  This middleware is designed for handling the multipart/form-data.

To install multer write following command:

$ npm install multer

To configure multer add following code in server.js:

app.use(multer({ dest: ‘./uploads/’,
rename: function (fieldname, filename) {
return filename+Date.now();
},
onFileUploadStart: function (file) {
console.log(file.originalname + ‘ is starting …’)
},
onFileUploadComplete: function (file) {
console.log(file.fieldname + ‘ uploaded to ‘ + file.path)
done=true;
}
}));

Multer emits event on particular situation such as we used onFileUploadStart which means when file start uploading, this event will be emitted.

As soon as onFileUploadComplete event emitted we have set the variable done to true and use it in our router to determine whether file is uploaded or not.

For handling routes, add following code in server.js:

app.get(‘/’,function(req,res){
res.sendfile(“index.html”);
});

app.post(‘/api/photo’,function(req,res){
if(done==true){
console.log(req.files);
res.end(“File uploaded.”);
}
});

To run server add following in server.js:

app.listen(3000,function(){
console.log(“Working on port 3000″);
});

Now, in your HTML file add following:

<form id = “uploadForm”
enctype = “multipart/form-data”
action = “/api/photo”
method = “post”
>
<input type=”file” name=”userPhoto” />
<input type=”submit” value=”Upload Image” name=”submit”>
</form>

In HTML form you must mention enctype=”multipart/form-data” else multer will not work.

Now run your project :

$ node server.js

And visit localhost:3000 to view running application.

To perform validation on Server end, multer provides limits array parameter. If you want you can perform validation as shown below:

app.use(multer({ dest: ‘./uploads/’,
rename: function (fieldname, filename) {
return filename+Date.now();
},
limits: {
fieldNameSize: 100,
files: 2,
fields: 5
}
}));

Multer provides easy way to upload files in Node.js.


ProsperaSoft offers Node.js development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Node.js experts and consultants.

 

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>