Nerd For Tech
Published in

Nerd For Tech

Upload images in Node.js without a form

Ever wanted to upload files without a form but find it too complicated? I got you.
This article gives you a simple example on how to upload files in express without a form.
To keep it simple, you can only upload jpg and png files in this example.

Btw this is the app directory

index.js
public
index.html
script.js

So first lets set up an express server which serves the public folder.

We will be using Multer to upload files, Multer is a middleware for Express.js used to upload files with ease. So now we added middleware with some configurations. For filename I’m using the upload time, you can change that easily to anything you want. Just make sure that the filename is unique (For example maybe use uuid).

Now we have to make a file input to send files and of course some JavaScript. Usually I love designing UI for an app, but I’m going to make this example as simple as possible, so I’m not adding CSS nor am I using any UI frameworks.

Main html page

So this is the main page of our app, notice that I specified the file type using the accept attribute of the file input tag.

Last but not least, the code!

Script for file upload

Basically all this does is, when you select a file, the upload button is enabled (via enableUpload()), and when it’s clicked a POST request with the file is sent to the server (uploadImage()). After the file is saved in the server, it returns file data as response. Then the URL of the image is taken by adding the base URL with the filename and it’s shown as an image. Also the file variable can be any blob file, for example an audio blob. Here the file variable contains the first file in the file input.

and Voila! you have a server that can save images for you kinda like Google Drive 😅 .

Here is the working example

Also there’s a GitHub repo if you want to fork this

On a side note I’m new to article writing and if you find any problem with this article please let me know!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store