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.
This tutorial needs minimal knowledge about Express.js and basic JavaScript
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).
We specified the destination of the files inside public folder so that the files can be easily accessible.
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.
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!
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!