Welcome folks today in this blog post we will be using the formidable
library to upload
files in node.js and express in browser using javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to create a new node.js
project using the below command as shown below
npm init -y
npm i express
npm i formidable
And after that you will see the below directory structure
of the express app as shown below
And now we need to make the index.js
file and copy paste the following code
index.js
1 2 3 4 5 6 7 8 9 10 11 |
var express = require('express'); var formidable = require('formidable'); var app = express(); app.get('/', function (req, res){ res.sendFile(__dirname + '/index.html'); }); app.listen(3000); |
As you can see we are importing the express
and formidable
library at the top and then we are loading the index.html
template when the user goes to the /
home route. And now we need to create the index.html
file inside the root directory and copy paste the following code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 |
<!DOCTYPE html> <html> <head> <title>Simple Upload Example</title> </head> <body> <form action="/" enctype="multipart/form-data" method="post"> <input type="file" name="upload" multiple> <input type="submit" value="Upload"> </form> </body> </html> |
As you can see we have the simple html5 user form
where we have the simple input field where we allow the user to select the file and then we have the upload
button. When we click the button we will be making the post
request to the /
route.
Now we need to make this post
request inside the index.js
file as shown below
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
app.post('/', function (req, res){ var form = new formidable.IncomingForm(); form.parse(req); form.on('fileBegin', function (name, file){ file.path = __dirname + '/uploads/' + file.name; }); form.on('file', function (name, file){ console.log('Uploaded ' + file.name); }); res.sendFile(__dirname + '/index.html'); }); |
As you can see we are first of all receiving the selected
file by the user using the IncomingForm()
method and then we are listening for various events
for uploading
the files. As you can see we are uploading the files
inside the uploads
directory.
Before executing this you need to create the uploads
directory inside the root directory where we will be storing the uploaded
files
node index.js