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
png files in this example.
Btw this is the app directory
So first lets set up an express server which serves the
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.
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
A simple way to upload files to Nodejs. Contribute to tomatopickle/File-Upload-Example development by creating an…
On a side note I’m new to article writing and if you find any problem with this article please let me know!