File Upload in Node.js Server
If you want to read full specification please go through THIS link.
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 storage
Where to store the filesfileFilter
Function to control which files are acceptedlimits
Limits of the uploaded datapreservePath
Keep 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 :
KeyDescriptionNotefieldname
Field name specified in the form originalname
Name of the file on the user's computer encoding
Encoding type of the file mimetype
Mime type of the file size
Size of the file in bytes destination
The folder to which the file has been savedDiskStoragefilename
The name of the file within the destinationDiskStoragepath
The full path to the uploaded fileDiskStoragebuffer
A 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.