File Upload in Node.js Server

chirag patel
2 min readJul 13, 2018

--

If you want to read full specification please go through THIS link.

https://www.codementor.tech/node-js-server-file-upload/

Start node project

Let us assume that you know how to setup node.js express project or you can learn from my previous article here.

package.json

{
"name": "nodejs-fileupload",
"main": "server.js",
"dependencies": {
"express": "4.13.3",
"multer": "1.1.0"
}
}

Installing the dependency. Now copy and paste above package.json save and run following command in terminal :

npm install

Now, go to the server.js and copy the following code :

var express =   require("express");
var multer = require('multer');
var app = express();
var storage = multer.diskStorage({
// file upload destination
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = multer({ storage : storage}).single('avatar');app.get('/',function(req,res){
res.sendFile(__dirname + "/index.html");
});
app.post('/api/avatar',function(req,res){
upload(req,res,function(err) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
});
app.listen(3000,function(){
console.log("Working on port 3000");
});

index.html

<form id        =  "uploadForm"
enctype = "multipart/form-data"
action = "/api/avatar"
method = "post"
>
<input type="file" name="avatar" />
<input type="submit" value="Upload Image" name="submit">
</form>

Copy and save the above code and run the node.js server by typing following command :

node server.js

Multer Storage options:

The following are the options that can be passed to Multer.

KeyDescriptiondest or storageWhere to store the filesfileFilterFunction to control which files are acceptedlimitsLimits of the uploaded datapreservePathKeep the full path of files instead of just the base name

Following is the snippet where you can see storage is defined. In multer.diskStorage() we have to set the file storage destination and filename can be changed as shown.

var storage =   multer.diskStorage({
// file upload destination
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
// custom function to change filename
var fileExtension = file.originalname.split('.');
callback(null, `${file.fieldname}-${Date.now()}.${fileExtension[fileExtension.length - 1]}`);
}
});

Each file contains the following information :

KeyDescriptionNotefieldnameField name specified in the form originalnameName of the file on the user's computer encodingEncoding type of the file mimetypeMime type of the file sizeSize of the file in bytes destinationThe folder to which the file has been savedDiskStoragefilenameThe name of the file within the destinationDiskStoragepathThe full path to the uploaded fileDiskStoragebufferA Buffer of the entire fileMemoryStorage

Conclusion:

Multer is very nice middleware created by Express community. It really helps us to quickly develop critical code like File uploads in Node.js easily. I hope you find this tutorial helpful.

Cheers!!

Happy Coding.

--

--

chirag patel
chirag patel

Written by chirag patel

Software Developer , Author @codemetor.tech

Responses (3)