Let's upload files using ExpressJs Server
Tags: node, express, beginners, multer
Published: 2019-12-19 08:55:41

Hi everyone ,

In this tutorial i will show how to upload images using ExpressJs server , using [multer](https://www.npmjs.com/package/multer).

To start  with let's created a brand new ExpressJs application.this is fairly easy so i won't focus on it much. if you want more you can check out my hello world in ExpressJs tutorial. And i'll use that same project from where we left off.

{% link https://dev.to/rizkyrajitha/build-your-first-expressjs-server-from-scratch-52c3 %}

after setting up your expressjs app . we have to install multer for file upload handling.so you know what to do right.

`npm i multer`

![install multer](https://thepracticaldev.s3.amazonaws.com/i/9kllqm3b88st4z2wt4im.PNG)

But what is multer anyway ? well....

[multer](https://www.npmjs.com/package/multer) is a Node.js middleware used to handle multipart form data, mostly used to upload files in Nodejs.So what it will do is grab the files we send from the client side as multipart form data and process them to a format so we can easily interact with them(store in disk , upload to another server etc). 

### keep in mind that multer will only process multipart formdata

OK now we know what multer is let's move on ...

There are two options we can have in multer to store received files.

1. disk storage - writes the file to directly to our file system 
2. memory storage - temporarily saves our file in memory(RAM) 

these 2 options have different use cases , but you can use it either way.

### let's start with file upload to disk. 

first of all import multer library

```const multer = require("multer");```

after that we need to create an object with the options we need when file storage. This will include **where we need to save the file in our filesystem** and also **what is the filename**.

you can specify any filename you want. for example if you need to keep track of the file upload time you can attach the timestamp to the file name by using `Date.now()` js date object . but keep in mind to append the original file format at the end of it.


```
var storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, "./"); //here we specify the destination. in this case i specified the current directory
  },
  filename: function(req, file, cb) {
    console.log(file); //log the file object info in console
    cb(null, file.originalname);//here we specify the file saving name. in this case. 
//i specified the original file name .you can modify this name to anything you want
  }
});
```

after that we need to specify the file which storage engine we are going to use.

`var uploadDisk = multer({ storage: storage });`

then create a brand new route called `/fileuploaddisk`. this route cannot be `GET` route . so i'll use a `POST` route . `PUT` can also be used. 

this route will first go through our multer middleware to process form data we are sending.then that middleware will grab our data and then it will save it in our local filesystem.

`uploadDisk.single("image")` is used to identify which form field contains our multipart data.here we specify image because in the frontend name of our multipart formdata field is `image`. you could use any name, but one should tally with the other.

in `uploadDisk.single("image")`, `single` stands for what type of multipart formdata we are expecting. `single` tells that we only send one file in this request.there are also other options like `array` so we can send multiple images.
for simplicity i'll go with `single` file. 

```
app.post("/fileuploaddisk", uploadDisk.single("image"), (req, res) => {
  console.log(" file disk uploaded");
  res.send("file disk upload success");
});
```
now the only thing left is to spin up our server. and also since we don't have a frontend , we can a api request builder to act as our front end.here i will be using [Postman](https://www.getpostman.com/)

now send a `POST` request to `http://localhost:5000/fileuploaddisk`

keep in mind to select body for your post request and use `form-data` in the request body options. then add a key with `image` since we specified our upload as `image` in backend. and also make sure you selected file. then the value will open a window to select your file. 

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/4pfvn3gayshmx75luziz.jpg)

and we successfully uploaded a file .

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/upiidzo2t6y92wdhyvc9.PNG)

____


disk storage `app.js`

{% gist https://gist.github.com/RizkyRajitha/dc4f53afdc4ff9da12d5c2d421b3b6c1 %}


### now let's  move on to file upload via memory storage.

it is also very similar to disk storage but we won't specify any options like before.

### keep in mind that since memory storage temporary store the files in our memory. it will use  a lot of memory if we upload large files , or large amounts of small files. but normal file sizes usage won't be affected .

since we already imported multer. But to write the file from memory to we need another module called 'fs' which is a module in Node.js for filesystem operations.'fs' is a builtin module in Node.js so we don't have to install anything.

`const fs = require("fs");`

next specify the storage engine.in this case we will specify memory storage.

```
var storage = multer.memoryStorage();
var uploadMem = multer({ storage: storage });
```

next we will create a new `POST` route `/fileuploadmem`.

reasons for `single` and `image` is same as the above example.But unlike disk storage memory storage middleware will not write file directly to the file system. it will process our request and then manipulates the `req` object and appends a new `file` object to it. `file` object have an attribute called `buffer` which contains our file in a buffer. so write that to an object we need the `fs` module. `fs.writeFileSync` method will write that buffer to our file system.

app.post("/fileuploadmem", uploadMem.single("image"), (req, res) => {
  console.log(req.file);
  fs.writeFileSync('./'+req.file.originalname , req.file.buffer)
  console.log(" file mem  uploaded");
  res.send("file mem upload success");
});


now let's test our memory upload with postman by sending a 
 `POST` request to `http://localhost:5000/fileuploadmem`.

keep in mind to select body for your post request and use `form-data` in the request body options. then add a key with `image` since we specified our upload as `image` in backend. and also make sure you selected file. then the value will open a window to select your file. 

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/2jis82jaeuqcocpcjzo7.jpg)

and we get our success message.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/tahopy9mwpxgq2uv250t.PNG)

____


memory storage `app.js`

{% gist https://gist.github.com/RizkyRajitha/8b265f67881e4b2c11c27a6c48259543 %}


#### now you will think that why to use memory storage , instead of using disk storage right away. but the thing is, if we used to upload the data to another cloud storage provider like [cloudinary](https://cloudinary.com/) , they accept a file as a buffer for uploading.so instead of writing to filesystem and the reading again we can simply send the buffer directly.

## Thank you for reading until the end. If you have any unclear part feel free to drop a comment and I'll try my best to help you out. and if you have suggestions please let me know in the comment section.

## Cheers 🥂 , Have a Nice Day. 
## And Have an awesome 2020 🎇✨🎉