ExpressJS - Handling File Uploads



It is a very common requirement where we need to upload file to the server. We can achieve the same functionality in express using multer library. multer is a middleware especially to handle multipart/form-data, primarily used to handle uploaded files.

Installing multer

We can use the following command to install multer using npm.

npm install --save multer

Usage

multer adds a file or files object to the request object. Using file object, we can retrieve the file details and using files, we can retrieve details of multiple files uploaded.

Handle single file upload

// upload a single file
app.post('/uploadFile', upload.single('uploadedFile'), function (req, res, next) {
  // req.file is the `uploadedFile` file
  const title = req.file.title;
  const file = req.file;
  const fileName = req.file.originalname;

  console.log(fileName + " saved in " + os.tmpdir());
  console.log(file);

  res.sendStatus(200);
})

Handle multiple files upload

// upload multiple files
app.post('/uploadFiles', upload.array('uploadedFiles', 12), function (req, res, next) {
  // req.files is the array of 'uploadedFiles' files
  const files = req.files;
  console.log("Files uploaded in " + os.tmpdir());
  console.log(files);

  res.sendStatus(200);
})

Example - Uploading a file to the server

Install required libraries if not present

Install the body-parser and multer, go to your terminal and use −

E:\Dev\hello-world>npm install --save body-parser multer
added 18 packages, and audited 128 packages in 1s

20 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

Replace your index.js file contents with the following code −

index.js

const express = require('express')
const multer  = require('multer')
const os = require('os'); 

// set the temp directory to upload a file
const upload = multer({ dest: os.tmpdir() })

const app = express()

// upload a single file
app.post('/uploadFile', upload.single('uploadedFile'), function (req, res, next) {
  // req.file is the `uploadedFile` file
  const file = req.file;
  const fileName = req.file.originalname;

  console.log(fileName + " saved in " + os.tmpdir());
  console.log(file);

  res.sendStatus(200);
})

// upload multiple files
app.post('/uploadFiles', upload.array('uploadedFiles', 12), function (req, res, next) {
  // req.files is the array of 'uploadedFiles' files
  const files = req.files;
  console.log("Files uploaded in " + os.tmpdir());
  console.log(files);

  res.sendStatus(200);
})

app.listen(3000);

Run your server

Run the server using following command.

E:\Dev\hello-world>nodemon index.js
[nodemon] 3.1.9
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting `node index.js`

Now go to postman and make a POST request with a file. The following response will be displayed −

Response to file upload

Have a look at your console; it will show you the body of your request as a JavaScript object as following −

E:\Dev\hello-world>nodemon index.js
[nodemon] 3.1.9
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting `node index.js`
Reliability.docx saved in C:\Users\TUTORI~1\AppData\Local\Temp
{
  fieldname: 'uploadedFile',
  originalname: 'Reliability.docx',
  encoding: '7bit',
  mimetype: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  destination: 'C:\\Users\\TUTORI~1\\AppData\\Local\\Temp',
  filename: '438bf0d2a7fe973cf49b28443db7c2f1',
  path: 'C:\\Users\\TUTORI~1\\AppData\\Local\\Temp\\438bf0d2a7fe973cf49b28443db7c2f1',
  size: 21279
}

The req.file object contains uploaded file data. Uploaded file is present in the temporary directory.

Advertisements