Skip to content

File uploads in express js 4

Last updated on November 17, 2022

In this tutorial, you will learn how to upload files to a remote server using node js in your express js application. You can upload any kind of file like images, videos, ZIP files, Microsoft Office documents, PDFs, as well as executable files, and a wide range of other file types.

Before you can use Express js/Node js to manage your uploads, you must first build an HTML form that lets users select a file to upload.

save as – index.html

<form action="api/v1/upload-photo" enctype="multipart/form-data" method="post">
<h2>Upload File</h2>
<label for="fileSelect">Filename:</label> <input name="file" type="file"><br><input name="submit" type="submit" value="Upload"></form>

multipart/form-data the form attribute is imported, without it, your form will not be able to upload files to the server. The enctype attribute can be used only if the method is “post”.The enctype attribute specifies how the form-data should be encoded when submitting it to the server.

Processing/Accessing the uploaded file

I am going to use express framework along with “multer middleware”. This middleware is designed for handling the multipart/form-data and it makes the uploaded files and form data available to us in request as request.files and request.body.

Let create a package.json file in a folder with the below json string and install dependencies by running npm install.

{
  "name": "expressjs-multer-file-upload",
  "version": "1.0.0",
  "description": "file uploading using multer",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.14.1",
    "multer": "^1.3.0"
  }
}

Now we have downloaded required dependencies, Let’s create a http server using express with below code –
save as – server.js

'use strict';
const express = require('express');
const app = express();
const multer = require('multer');

let storage = multer.diskStorage({
    destination: function (req, file, callback) {
        callback(null, __dirname + '/uploads/'); // set upload directory on local system.
    },
    filename: function (req, file, callback) {
        callback(null, file.fieldname + '-' + Date.now()); // appending current date to the file name.
    }
});

let upload = multer({ storage: storage }).single('file'); // file upload handler , should be same same as form element name

app.get('/', function (req, res) {
    res.sendFile(__dirname + "/index.html"); // load html form
});

app.post('/api/v1/upload-photo', function (req, res) { // process the input request
    upload(req, res, function (err) { 
        if (err) {
            return res.end("Error uploading photo.");
        }
        res.end("Photo is uploaded successfully.");
    });
});


// Start web server at port 3000
let port = 3000;
let server = app.listen(port, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log(`Server start at http://${host}:${port}`);
});

There is just one more thing to have in mind. You have put the use same name to your input element of the type file and backed multer config name, here in the above code we are using “file”.

Running project – Run the below command from the root of your project to run the project.

npm server.js

Now Visit http://localhost:3000 to view the app. Select the file and click on the upload button. The file should be present in the uploads directory, check the uploads folder.

req.files the variable holds the following array of information for each uploaded file.

originalname – Name of the file on the user’s computer
name – Renamed file name
encoding – Encoding type of the file
mimetype – Mime type of the file
path – Location of the uploaded file
extension – Extension of the file
size – Size of the file in bytes
truncated – If the file was truncated due to size limitation
buffer – Raw data (is null unless the in-memory option is true)

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments