Simplest Uploader? Creating Powerful Node.js Object Uploader
Tags: node, javascript, webdev, tutorial
Published: 2022-05-12 19:21:21

Uploading Objects to the server is one of the Key Concepts of backend development and web development in general.

it's quite rare to see a website without images, most of the time these websites are not static and the images, as well as details, are managed from an Admin Panel Dashboard, Or you have seen Forms in websites to attach a file with the details.

An Uploader is your way on how to let the server handle the upcoming files from the client-side.

in this article, we will discuss creating a file uploader that is not limited to a type of file but rather works for almost all of the file types and without **using any extra package**.

- **Nowadays approaches for creating an Uploader versus what we are building**

There are two common methods to send a file to the server ( the whole file, so no streams here )

1. Sending File as Form-data: For example, submitting an HTML form with attached files to it will be labeled as Multipart.
This usually requires a body parser that can parse this complex data from the body such as [Multer](https://www.npmjs.com/package/multer). 

2. Sending File as String: Such as converting the File to base64 encoding and sending it as JSON in the Body.
one thing you should be aware of, Base64 encoding writes each 3 bits as 4 bits which increases the file size by up to %30.


What we are doing :

1. We won't be using any parser for the multi-part to keep it simple, thus we accept the base64 or image text area.
2. even though the size increases, you shouldn't use this method for very large files and it doesn't make a lot of difference in small files(up to 100MB). 
3. we only use functions of Node.js's Fs modules


There are a lot of packages out there, but sometimes your needs are just simple things to accept anything with no restrictions.


So let's begin

any file that hits this API should be encoded with base64, you can find many libraries to have base64 uploader in Front-End

I have got this 1px by 1px image, just to not get the string too large.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tlfb07z17jf76u6b914z.png)

I have converted it to base64 from an online converter [Base64 encoder](https://www.base64-image.de/)

Let's start Coding 

Creating new node.js project =>

First I will run this to create a node.js project

```
npm init
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1s9yxpc4ts2d9yi7t6pq.png)

Then I will create index.js as our playground for our uploader.
 
At First, I will import Node.js's Fs core module and put our base64 example in the file.

```js
const fs = require("fs").promises;

let exampleImage = "data:image/png;base64,
iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAAXNSR0IArs4c6QAAAAxJREFUGFdjcOyfCQACfgFqcbSa6QAAAABJRU5ErkJggg=="

```

Then we will add our function upload, simply we will have a name and which I hardcoded the file suffix for simplicity but usually, base64 encoded string also includes the file type and you can put it as name.${extract the file suffix}.


```js

const upload = async (base64) => {
  const fileSuffix = "png"
  const name = `anyFileName.${fileSuffix}`
  const dir = `${__dirname}/file/${name}`;
  const base64Data = Buffer.from(
        base64.replace(/^data:image\/\w+;base64,/, ""),
        "base64"
      ); 
  await fs.writeFile(`${dir}`, base64Data);
};

```

then we will have the directory we want to save and basically extract the base64 from the Base64Data and turn it into a buffer.

lastly we write the data to the specified folder .


then run the function 

```js
upload(exampleImage);
```


this is the result of running the program with 

```
node index.js
```

the output is that we have successfully saved an image.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dyhw3s292n7o97g68hxx.png)

With only this, you can save any object you want .. you need the base64 and simply what that file is that is uploaded. if it's a PDF or Image or any file.



Thanks for reading this article.