Procedure
Create a directory
Create a directory for the project and type the command npm init to create a package.json file.
make a new directory-
mkdir file-upload-multer
move to the following directory-
cd file-upload-multer
initialize npm-
npm init
Installation of dependencies
Install the required dependencies
npm install express multer --save
OUTPUT-
Create server.js file
Create server.js by using the touch command, or if it doesn't work, use
type nul >server.js
or
echo >server.js
Creating server
Create server using express.js by opening server.js file and typing following code-
var express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('hello developers');
});
app.listen(port, () => {
console.log('we are listening to the port: ' + port);
});
After typing the code, we have to save the file and run it using the command
node server.js
OUTPUT-
To see the result, type the following URL
http://localhost:3000
OUTPUT-
Congratulations! you have come so far and covered halfway.
Adding Multer
now add multer
var multer = require('multer');
var upload = multer({dest:'uploads/'});
Here dest denotes the destination of the file where it will be stored. Furthermore, we create an endpoint that will upload the file.
app.post('/single', upload.single('profile'), (req, res) => {
try {
res.send(req.file);
}catch(err) {
res.send(400);
}
});
Single files and multiple files can be uploaded with the help of Multer in node.js. Here upload.single command is for uploading a single file. A file object is added by Multer to the request. Metadata related to the file will be stored in this file object.
OUTPUT-
For better understanding have a look at this video -
Now you will notice the uploaded folder will be created in dest option means destination location, but the uploaded file will not contain any extension. We use the storage option instead of dest for having more control. Multer ships with storage engines DiskStorage and MemoryStorage.
Use of DiskStorage
Use DiskStorage. We get complete control of storing files on a disk by using a disk storage engine. We will use the following code for creating storage.
var storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, './upload');
},
filename: function (req, file, cb) {
cb(null , file.originalname);
}
});
and update upload variable
var upload = multer({ storage: storage })
We have two options, destination and filename, available, which are functions used to determine where the file should be stored.
The folder in which the uploaded files should be stored is determined by destination. We can also be given a string, for example, '/desktop/upload .'operating system's default directory is used for storing temporary files when we don't provide any value for the destination.
Creating the directory is our responsibility while providing the destination as a function—Multer whether the directory is created for you or not when we pass the string into it.
Furthermore, the file's name inside the folder is defined by filename, but if we don't give any representation, it is given any random name with no extension. As multer does not add an extension to your file, you must return the file name with the extension.
Both the request (req) are passed by each function and some information about the file (file) to aid the decision. If you want to have the same file name while saving, they were uploaded for that use file.originalname, I am using file.originalname, or you can use any name of your choice. after hitting the endpoint, you will notice that the uploaded files will be present in the mentioned folder with the same extension and name.
Now, a single file is uploaded successfully using multer. Similarly, we can upload multiple files, and we use a bulk endpoint for uploading multiple files.
app.post('/bulk', upload.array('profiles', 4) , (req, res) =>{
try {
res.send(req.files);
} catch(error) {
console.log(error);
res.send(400);
}
});
Here upload. array is used instead of upload—single, which adds in the request object, an object files.
It would help if you got on hitting the bulk endpoint.
Frequently Asked Questions
- What is node.js?
A backend javascript runtime environment that is open source and cross-platform also runs on the v8 engine. It contains many packages, and one of them was a Multer in node.js about which we learned in this blog.
2. What is express.js?
It is a backend web application node.js framework, open-source software with an MIT license.
Key Takeaways
Don't come to a halt here. Check out our Top 10 NodeJS Frameworks In 2021 | Coding Ninjas Blog. You can also check out the blog on the What is Node.js? Where, When & How To Use It? | Coding Ninjas Blog. Check out some books for react.js PHP vs NodeJS: A complete showdown | Coding Ninjas Blog, JavaScript environment requirements.