File uploads in express js 4

In this tutorial you will learn how to upload files on remote server using node js in your express js application. You can upload any kind of file like images, videos, ZIP files, Microsoft Office documents, PDFs, as well as executable files and a wide range of other file types.

Before you can use Express js/Node js to manage your uploads, you must first build an HTML form that lets users select a file to upload.

save as – index.html

multipart/form-data form attribute is import, without it your form will not be able to upload files to the server. The enctype attribute can be used only if method is “post”.The enctype attribute specifies how the form-data should be encoded when submitting it to the server.

Processing/Accessing the uploaded file

I am going to use express framework along with “multer middleware”. This middleware is designed for handling the multipart/form-data and it makes the uploaded files and form data available to us in request as request.files and request.body.

Let create a package.json file in a folder with below json string and install dependencies by running npm install.

Now we have downloaded required dependencies, Let’s create a http server using express with below code –
save as – server.js

There is just one more thing to have in mind. You have put the use same name to your input element of type file and backed multer config name, here in the above code we are using “file”.

Running project – Run below command from root of your project to run project.

Now Visit http://localhost:3000 to view the app. Select the file and click on upload button. File should present in uploads directory, check the uploads folder.

req.files variable holds following array of information for each uploaded file.

originalname – Name of the file on the user’s computer
name – Renamed file name
encoding – Encoding type of the file
mimetype – Mime type of the file
path – Location of the uploaded file
extension – Extension of the file
size – Size of the file in bytes
truncated – If the file was truncated due to size limitation
buffer – Raw data (is null unless the inMemory option is true)

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

Arjun
I am Arjun from Hyderabad (India). I have been working as a PHP Developer from last 6+ years, and its my passion to learn new things and implement them as a practice. Aside from work, I likes gardening and spending time with pets.