Android

File upload in Node.js

Wordpress

In this tutorial will learn how to upload any file to the node.js server. File upload in node.js seems tedious due to its async nature and network programming approach. However, it is one of the easiest file upload mechanism I have come across.

Introduction

We will be using node.js + express. We will be using “multer” as middleware. This middleware is designed to handle the multipart/form-data which is primarily used to upload files.

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

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

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

index.html

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

Multer Storage options:

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

Key Description
dest or storage Where to store the files
fileFilter Function to control which files are accepted
limits Limits of the uploaded data
preservePath 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.

Each file contains the following information :

Key Description Note
fieldname 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 saved DiskStorage
filename The name of the file within the destination DiskStorage
path The full path to the uploaded file DiskStorage
buffer Buffer of the entire file MemoryStorage

 

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.

LEAVE A REPLY

Please enter your comment!
Please enter your name here