Preloader
Drag

I’m going to explain to you a topic that many of us find intimidating but is actually quite simple: “Uploading files from the frontend to a Node.js server.”

This technique, which can be used for various purposes including image uploads, might seem like storing the data as a blob in a database is a solution, but it’s actually a very unhealthy and risky approach. That’s why I recommend you learn what I’m about to explain.

First, why should we avoid storing data as blobs?

  • Blob data takes up a lot of space in the database and degrades database performance.
  • As the database grows, your blob data may become corrupted.
  • It’s not possible to manipulate data stored as blobs (e.g., compressing images, changing their format).

Now, let’s get to the main topic. To quickly transfer your files from the frontend, you simply need to add an input (type: file) and connect it to the backend.

The Node.js code example I’ve provided below saves the sent data to the “uploads” folder on the server with a unique name based on the current date and time. You can then store the file path of this data in your database if you wish. This will significantly improve your database performance compared to using blobs.

If you’re using this code for image uploads, you can also add the sharp and fs libraries to compress the saved image and convert it to the webp format, thus improving the image upload performance of your page.

NOTE: You need to check the metadata of the uploaded file during these operations. Otherwise, you may allow files that look like images (based on an image file) but are actually not images and have an image extension to be uploaded to your server.

I hope this is helpful, happy coding everyone! 🙂