Uploading an Image using Multer in Nodejs and Angular Project

Sai Kiran
3 min readAug 1, 2020

--

Writing a File upload API is really important for many projects where they have to upload different type of files or images to upload into their server. In NodeJs we have an middleware tool which helps us to upload files from the fronted to the NodeJs server.

Let’s start with Angular application where we have send the file to Nodejs server.

Writing the input field of type file in the angular reactive form. After click the submit button, it will run the submitPhoto function.

In the ‘fileChoosen’ function it will create file type and store it in ‘this.image’ variable. In ‘submitPhoto’ function it create a formdata array and append ‘this.image’ with tag ‘profileImage’. We will send this formdata array to the the backend server API using a post request.

This completes the frontend part of the code to send the file to backend. Now let’s look at how to write the Api using ‘Multer’ in NodeJs to store the File in the server.

Let’s install the Multer middleware using npm tools. Open the NodeJs Server project and type the following command in the terminal. This will install multer middleware for you project.

npm install multer

Now create a file named fileUpload.js in your project and import the multer into the file.

const multer = require(‘multer’);

Now let’s write the function which configures the images settings and stores the images into the destination specified in the settings.

In the above function, the image storage has various attributes we have used destination where the images are being stored and filename. imageFileFilter specifies the types of files accepted by the API and other than that it throw an error.

This is the API which frontend sends the data. We will call the imageUpload function as the middleware of this API which sends formData array to the imageUpload function. In this API, it will check whether the username is valid or not and stores the image location into the userData with ‘profileImage’ tag. And send the result to the fronted as the ‘success:true, status:Profile ImageUploaded Successfully’.

You can write similar code to Upload your files to AWS S3 buckets as well.

I hope you have successfully implemented the Fileupload into your NodeJs application. If you have any queries you can reach me out saikiran1298@gmail.com

Thank You!!

--

--

Sai Kiran

Engineering @Walmart | Software Engineer & Technology Enthusiast