Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Node.js Express Single & Multi File Input Fields Upload Example Using express-fileupload Library in Browser Using Javascript

Posted on October 13, 2022

 

 

Welcome folks today in this blog post we will be uploading files to server in node.js and express using the express-fileupload library 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 initialize a new node.js project and install the following dependencies as shown below

 

 

npm init -y

 

 

npm i express

 

 

npm i express-fileupload

 

 

As you can see we are initializing a new package.json file and then installing the express and express-fileupload library which is a middleware function or library inside express.js to upload the files to the express server. It’s a great alternative to the multer library. Here we can upload the single and multiple files.

 

 

Uploading a Single File

 

 

Now we will be uploading a single file to the express.js server. First of all we will be importing the required libraries and also include the express-fileupload middleware to the express app as shown below. Lastly we will be starting the express app at port 3000

 

 

1
2
3
4
5
6
7
8
9
10
11
12
const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();
 
// default options
app.use(fileUpload());
 
app.get('/',(req,res) => {
    res.sendFile(__dirname + "/index.html")
})
 
app.listen(3000)

 

 

As you can see here we are making a simple get request to show a simple html5 form where the user will upload the file using the input field. Now we need to make this index.html file which will be shown when we open the home page or home route. And also make a uploads folder where we will be storing all the uploaded files

 

 

 

 

 

index.html

 

 

1
2
3
4
5
6
<form action="/upload" enctype="multipart/form-data" method="post">
    <div class="form-group">
        <input type="file" class="form-control-file" name="file">
        <input type="submit" value="Upload File" class="btn btn-default">
    </div>
</form>

 

 

As you can see we have the simple html5 form where we have the action attribute which will go to /upload and the method is post and we are also providing the enctype attribute as well because here we are uploading files. And inside the form we have a simple input field of type file and we have given a name attribute which is very important for file uploading. We will use it in the index.js file (server side code) later on. And then we have the submit button to submit the form

 

 

Writing the POST Request to Upload File

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
app.post('/upload', function(req, res) {
  let sampleFile;
  let uploadPath;
 
  if (!req.files || Object.keys(req.files).length === 0) {
    return res.status(400).send('No files were uploaded.');
  }
 
  // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
  sampleFile = req.files.file;
  uploadPath = __dirname + '/uploads/' + sampleFile.name;
 
  // Use the mv() method to place the file somewhere on your server
  sampleFile.mv(uploadPath, function(err) {
    if (err)
      return res.status(500).send(err);
 
    res.send('File uploaded!');
  });
});

 

 

As you can see in the above code we are basically first of all declaring two variables for the file and the uploadPath and then we are checking whether any file is selected or not. If no file is selected then we will show error message that please upload a file which is validation error. And after that we are providing the path where the file will be uploaded. It will be uploaded inside the uploads folder we created And then we are extracting the filename as well. And lastly we are using the mv() method of file object to actually upload or move the file to the outputPath and if any error takes place we are displaying the error. If no error takes place then we are sending the response file uploaded.

 

 

Uploading Multiple Files

 

 

Now we will write the code for uploading multiple files. For doing this first of all we will making an another html file called multiple.html file inside the root directory and we will make an another get route for showing this

 

 

JavaScript
1
2
3
app.get('/multiple', (req, res) => {
    res.sendFile(__dirname + "/multiple.html")
})

 

 

As you can see we are loading the multiple.html file when we go to /multiple route. So we will define the multiple.html file

 

 

1
2
3
4
5
6
<form action="/uploadmultiple" enctype="multipart/form-data" method="post">
    <div class="form-group">
        <input type="file" class="form-control-file" name="files" multiple>
        <input type="submit" value="Upload Files" class="btn btn-default">
    </div>
</form>

 

 

As you can see we have a html5 form with action attribute equal to /uploadmultiple. We have the post request when the form submits and inside this we have the input field which is accepting multiple files using the multiple attribute. Also we have assigned the name attribute which is very important in uploading the files. And then we have the submit button to submit the form.

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
app.post('/uploadmultiple', function (req, res) {
    // Uploaded files:
    console.log(typeof req.files.files)
 
    let sampleFile;
    let uploadPath;
 
    if (!req.files || Object.keys(req.files).length === 0) {
        return res.status(400).send('No files were uploaded.');
    }
 
    req.files.files.forEach(file => {
        sampleFile = file.file
        uploadPath = __dirname + "/uploads/" + file.name
 
        file.mv(uploadPath,(err) => {
            if (err)
            return res.status(500).send(err);
        })
    });
 
    res.send("All files uploaded")
});

 

 

As you can see we have the post request to upload multiple files. Inside this request we are again using the foreach loop to loop through each file which has uploaded. The array is stored in req.files.files. And we are looping through an array. First of all we are checking if no files are present inside this array then we are returning an error message. And after that we are using the mv() function of each file object to move the files from one location to another. After that we are sending the response to the user that all files have been uploaded successfully.

 

 

Uploading Files From Multiple Input Fields

 

 

Now let’s suppose you have more than one input field to allow the user to choose a file. Let’s suppose you have three input fields where you need to allow to user to upload files. In that scenario we will look how to upload files from different input fields.

 

For this we will make amultiplefields.html file and copy paste the following code

 

 

multiplefields.html

 

 

1
2
3
4
5
6
7
<form action="/multiplefields" enctype="multipart/form-data" method="post">
    <div class="form-group">
        <input type="file" name="my_profile_pic" />
        <input type="file" name="my_pet" />
        <input type="file" name="my_cover_photo" />
    </div>
</form>

 

 

So as you can see we are making the post request to /multiplefields route. Inside this form you can see we have three input fields each having a unique name attribute. Now to get out the name and to upload them we will be making a post request to the route /multiplefields

 

 

JavaScript
1
2
3
4
5
app.post('/multiplefields',(req,res) => {
    console.log(req.files.my_profile_pic.name);
    console.log(req.files.my_pet.name);
    console.log(req.files.my_cover_photo.name);
})

 

 

As you can see in this post request we are getting the filenames of the uploaded file.

 

 

FULL SOURCE CODE

 

 

Wrapping it up this is the full source code of the index.js file which is shown below

 

 

index.js

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();
 
// default options
app.use(fileUpload());
 
app.get('/', (req, res) => {
    res.sendFile(__dirname + "/index.html")
})
 
app.get('/multiple', (req, res) => {
    res.sendFile(__dirname + "/multiple.html")
})
 
app.get('/multiplefields',(req,res) => {
    res.sendFile(__dirname + "/multiplefields.html")
})
 
app.post('/multiplefields',(req,res) => {
    console.log(req.files.my_profile_pic.name);
    console.log(req.files.my_pet.name);
    console.log(req.files.my_cover_photo.name);
})
 
 
app.post('/uploadmultiple', function (req, res) {
    // Uploaded files:
    console.log(typeof req.files.files)
 
    let sampleFile;
    let uploadPath;
 
    if (!req.files || Object.keys(req.files).length === 0) {
        return res.status(400).send('No files were uploaded.');
    }
 
    req.files.files.forEach(file => {
        sampleFile = file.file
        uploadPath = __dirname + "/uploads/" + file.name
 
        file.mv(uploadPath,(err) => {
            if (err)
            return res.status(500).send(err);
        })
    });
 
    res.send("All files uploaded")
});
 
app.post('/upload', function (req, res) {
    let sampleFile;
    let uploadPath;
 
    if (!req.files || Object.keys(req.files).length === 0) {
        return res.status(400).send('No files were uploaded.');
    }
 
    // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
    sampleFile = req.files.file;
    uploadPath = __dirname + '/uploads/' + sampleFile.name;
 
    // Use the mv() method to place the file somewhere on your server
    sampleFile.mv(uploadPath, function (err) {
        if (err)
            return res.status(500).send(err);
 
        res.send('File uploaded!');
    });
});
 
app.listen(3000)

 

Recent Posts

  • Build a JWT Login & Registration Auth System in Node.js & Express Using MongoDB in Browser
  • React-Admin Example to Create CRUD REST API Using JSON-Server Library in Browser Using Javascript
  • Javascript Papaparse Example to Parse CSV Files and Export to JSON File and Download it as Attachment
  • Javascript Select2.js Example to Display Single & Multi-Select Dropdown & Fetch Remote Data Using Ajax in Dropdown
  • Video.js Video Player Plugin Library in Javascript For Playing Videos in Browser
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme