How to upload multipart or Image file via Node Js

Ankit dwivedi
2 min readMay 15, 2023

--

Hello folks today we will see how to upload files in Nodejs backend.

To upload a multipart or image file via Node.js, we can use the multer middleware package. Multer is a popular middleware package in Node.js that provides support for handling multipart/form-data, which is primarily used for uploading files. It provides an easy way to handle file uploads by parsing the incoming FormData object, extracting any uploaded files, and storing them in a specified location.

I assume you already familiar with node, npm and javascript.

Enough theory part, Now let’s get started…

Step -1 : Install multer in your node project

> npm install multer

Step -2 : require in your file

You can include it in your Node.js application like this

Once you’ve required multer, you can create an instance of it using the multer() function. You can then specify options such as the destination directory where files will be stored and the maximum file size allowed.

Upload Single file

We’ve successfully created an instance of multer and specified that uploaded files should be stored in the uploads/ directory. We've also specified that the maximum file size allowed is 1 MB. We use the upload.single() method to specify that we are expecting a single file upload with the field name file. Once the file is uploaded, the callback function is called and a success message is sent back to the client.

Upload multiple files in nodejs

To upload multiple files we can use array like :

use the array method of multer to handle multiple files with the same field name files in the form data.

In the route handler function, we can access the uploaded files via req.files, which will be an array of files. We can then perform any necessary operations on these files, such as storing them in a database or processing them in some way.

Note that the array method of multer accepts an optional second argument that specifies the maximum number of files to accept. For example, to accept up to 5 files, you can call upload.array('files', 5).

--

--

Ankit dwivedi
Ankit dwivedi

Written by Ankit dwivedi

Software developer ? ( Flutter || Dart || IOS ||C# || Nodejs || Kotlin || Java || Android ) : Writing

No responses yet