DEV Community

Cover image for Simplest Uploader? Creating Powerful Node.js Object Uploader
Ali Amjad
Ali Amjad

Posted on

Simplest Uploader? Creating Powerful Node.js Object Uploader

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.

  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

I have converted it to base64 from an online converter Base64 encoder

Let's start Coding

Creating new node.js project =>

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

npm init
Enter fullscreen mode Exit fullscreen mode

Image description

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.

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

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

Enter fullscreen mode Exit fullscreen mode

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}.


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);
};

Enter fullscreen mode Exit fullscreen mode

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

upload(exampleImage);
Enter fullscreen mode Exit fullscreen mode

this is the result of running the program with

node index.js
Enter fullscreen mode Exit fullscreen mode

the output is that we have successfully saved an image.

Image description

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.

Oldest comments (4)

Collapse
 
kodoyousif profile image
kodo-yousif

easy and nice, Thanks

Collapse
 
ali_a_koye profile image
Ali Amjad

^_^

Collapse
 
mohammedjaffer profile image
Mohammad-svg

Hey Ali,

Great job here on dev.to. You know what?

I read a lot of blog posts and I never heard of a topic like this. This is so chock full of useful information. Very ingenious.

Collapse
 
ali_a_koye profile image
Ali Amjad

Thanks <3