Upload Files to Node.js Back-End Through an Express API Using Multer

Upload Files to Node.js Back-End Through an Express API Using Multer

By the end of this tutorial, you will be able to set up your own API from scratch in a Node.js back-end based on Express and Multer. This API will catch a file sent over a POST request and will store it in a folder on your back-end server.

API to upload file in NodeJS using Express and MulterPhoto by Arnold Francisca on Unsplash

Note that in this tutorial we don’t explain the “Express part” (used to set up the API and how it works). If you need to learn more then go to this quick and simple tutorial:

What is an API?

API stands for an application programming interface. It is the back-end side of your web application and it’s usually run on your server. The API is always used to serve your front-end and can be also used as an interface to be integrated by a third party. An API is composed of a collection of services to get or push data to your back-end server.

What do you need?

I’ll assume that you have already installed Node.js (if not, please check the tutorial mentioned above).

Now you have to initiate your node project by:

npm init

You need to install:

  • Express: to create the API
  • Multer: to handle the file upload

You can install them using this command:

npm install --save express multer

But what is Express?

Express.js, or simply Express, is a back-end web application framework for Node.js, released as free and open-source software under the MIT License. It is designed for building web applications and APIs.[3] It has been called the de facto standard server framework for Node.js.” -Wikipedia

And Multer?

“Multer is a Node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.” https://github.com/expressjs/multer

Coding time!

In the following example, we will set up an API in order to catch HTTP POST to upload a file to our server running on Node.js :

The server will listen on port 3000 and when it catches a POST request for “/uploadfile” it will handle it.

Note that you have to create a folder where you will store the uploaded files. In this example, the folder is named “uploadedFiles”.

This is how it looks inside your project:

upload file to nodeJS server with express and multerProject organisation

  • note_modules: is the folder including all node modules used and installed for this project.
  • uploadedFiles: the folder we created in which we will store all the files uploaded to the server.
  • app.js: the server code to be run on the Node.js server.
  • package.json: project config and dependencies.

Now if we take a look at our JavaScript code in which we create the API with Express and Multer to handle file upload:

Let’s walk through the code!

Here we are importing Express and Multer modules:

const express = require('express');

const multer = require('multer');

Now we will set up Multer to use it. First of all, we need to create and set up the file storage engine in which we have to configure where the files will be stored and we can also set how Multer will handle filename when a file is uploaded:

  • in the “destination” option we have specified the storage folder ‘uploadedFiles/’.
  • in the name option, we have specified that we will use the original file name as it was uploaded.

Note that in the two options there is a cb: which is the callback to determine the destination path for the 1st option and the callback to determine the name of the uploaded file for the second option.

// set up multer

var storage = multer.diskStorage({

destination: function (req, file, cb) {

cb(null, 'uploadedFiles/')

},

filename: function (req, file, cb) {

cb(null, file.originalname)

}

})

Now we can instantiate Multer with the storage config defined above.

var upload = multer({ storage: storage })

Now let’s create the Express app which will handle the API and then start listening:

// create app

port = 3000;

const app = express();

app.listen(port,()=>{

console.log("Server started on port :"+port)

});

The final step is to code the part of the app which will catch the POST request and use Multer to handle the uploaded file:

app.post('/uploadfile', upload.single('filetoupload'),
function (req, res, next) {

console.log(req.body.description);

res.status(200).send({'message' : "file uploaded"});

})

  • app.post: used to handle POST requests and will invoke “function”.
  • ‘/uploadfile’: to set up with what URL path the request handler will be fired.
  • upload.single(‘filetoupload’): here we are saying to the request handler that we will handle an uploaded file with Multer. The file must be uploaded using the field ‘filetoupload’ when you build and send the request on the front-end side.
  • console.log(req.body.description): longing the description message sent in the JSON with the uploaded file (it is optional but can be helpful).
  • res.status(200).send({‘message’: “file uploaded”}): we are sending a status 200 to say that everything is OK and returning a message in a JSON to the Front-end.

Now let’s test it!

Start your app by running the node command:

node app.js

If the app is started you will see:

app started and API running

To test the API, we will use the Postman tool (a really powerful tool when developing API).

Check here:

Let’s launch our API test:

test the nodeJS API(with Express and Multer) to upload a fileTest Express API to upload file

And the result?

API test result

We are getting a 200 status code, which means that everything is OK and we are receiving the message from the server: “file uploaded”.

Awesome isn’t it ?!

But wait, is the file really stored in the server?!

uploaded file stored in the server

You can see that the file was successfully stored on the server.

Conclusion

By the end of this tutorial you learned how to:

  • Install Express and Multer modules.
  • Configure the Multer storage engine and Multer instance to handle the uploaded file.
  • Develop a POST API handler with Express.
  • Integrate Multer middleware in your API handler to handle the uploaded file and store it correctly in the storing folder created on the back-end server.

Hope it was helpful! Check my tutorials here.

Please don’t forget to hit the button “follow”.

You can support me and other authors by joining the Medium community, follow the link: