How To Upload Files To The Server In Node.js

node.js file upload tutorial

File uploads are a fundamental part of many web applications, and Node.js provides a simple way to handle them. In this step-by-step tutorial you will learn how to upload files to the server through HTML form in Node.js using one of the popular file-uploading library “express-fileupload”.

Step 1: Create a Node.js Project Folder

Begin by creating a new directory called file-upload-app for your Node.js project. Then go inside the project folder and initialize the npm.

mkdir file-upload-app
cd file-upload-app
npm init -y

Here is the structure to the file-upload-app folder –

node file upload folder structure

Step 2: Install the “express” & “express-fileupload” Package

npm install express express-fileupload

Step 3: Create HTML Form for Uploading Files

Create index.html at the root and add an HTML form in that allows users to select and submit files. Must add the enctype attribute set to "multipart/form-data" to enable file uploads. Here is the Html code –

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Node js File Upload</title>
        <link
            rel="stylesheet"
            href="https://cdn.jsdelivr.net/npm/water.css@2/out/water.css"
        />
    </head>
    <body>
        <form action="/upload" method="post" enctype="multipart/form-data">
            <label for="myFile">Choose a File</label>
            <input type="file" name="myfile" id="myFile" />
            <input type="submit" value="Upload" />
        </form>
    </body>
</html>

In this code the form will send a POST request to the /upload route when a user clicks the “Upload” button. The name="myfile" is an important attribute because we can access the file in the /upload via the name which is myfile.

Step 4: Handling File Uploads in Node.js

Now, it’s time to set up your Node.js application to handle file uploads. Create a JavaScript file called app.js and add the following code:

const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();
const port = process.env.PORT || 3000;

// Middleware to parse JSON and urlencoded request bodies
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Enable file uploads middleware
app.use(fileUpload());

// Serve the HTML form
app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

// Handle file uploads
app.post('/upload', (req, res) => {
    // If there is no file to upload
    if (!req.files || Object.keys(req.files).length === 0) {
        return res.status(400).send('No files were uploaded.');
    }

    // Get the uploaded file
    const targetFile = req.files.myfile;

    // If myfile is missing
    if (!targetFile) return res.send('myfile is missing!');

    // Extract filename and define upload path
    const fileName = targetFile.name;
    const uploadPath = __dirname + '/uploads/';
    const filePathName = uploadPath + fileName;

    // Move the uploaded file to the target directory
    targetFile.mv(filePathName, (err) => {
        // If there is an error while moving the file
        if (err) {
            return res.status(500).send(err.message);
        }
        res.send('File uploaded!');
    });
});

// Start the server
app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});

In the code, you can see the targetFile.mv() function which is responsible for uploading files. This .mv() function takes two parameters –

  • filePathName – Full path to the directory (where the file will be stored) with the name.
  • callback – A callback function with error parameter for handling errors.

Step 5: Handling File Upload Errors

The code provided (app.js) includes basic error handling. If there are no files in the request or an error occurs during the file upload, the server responds with appropriate status codes and error messages. You can also use the try-catch to handle errors:

app.post('/upload', async (req, res) => {
    try {
        const targetFile = req.files.myfile;
        await targetFile.mv();
        res.send('File uploaded!');
    } catch (e) {
        return res.status(500).send(err.message);
    }
});

Step 6: Test the Application

Now start the application and test it.

node app.js

Visit http://localhost:3000 in your web browser, and you should see the file upload form. Select a file and click “Upload” to test the file upload functionality.

More on “express-fileupload”

1. Store temporary files:

By default, this module uploads files into RAM. Turning on the useTempFiles option by setting it to true enables the use of temporary files instead of utilizing RAM.

This option prevents memory overflow issues when uploading large files or when uploading multiple files simultaneously.

// From this
app.use(fileUpload());

// To this
app.use(
    fileUpload({
        useTempFiles: true,
    })
);

By default this module uses 'tmp' folder in the current working directory. If you want to use custom folder to store temporary files use tempFileDir along with the useTempFiles.

app.use(fileUpload({
    useTempFiles : true,
    tempFileDir : __dirname + '/tmp_folder',
}));

2. Limiting the Upload File Size

You can limit the upload file size with the help of the limits: in-bytes option. Here is an example:

// Enable file uploads
app.use(
    fileUpload({
        useTempFiles: true,
        limits: { fileSize: 1 * 1024 * 1024 }, // Maximum file size is 1MB
    })
);

// Handle file uploads
app.post('/upload', (req, res) => {

    const targetFile = req.files.myfile;
    // If the file is over the size limit
    if (targetFile.truncated) {
        return res.send('File is too large max size is 1MB');
    }

    targetFile.mv(filePathName, (err) => {
        if (err) {
            return res.status(500).send(err.message);
        }
        res.send('File uploaded!');
    });

});

3. Rename the File Before Uploading

We need to rename the file before storing, so that the new file cannot replace the old file, and it is quite easy task. Here is an example of renaming file while using express-fileupload in node.js:

app.post('/upload', (req, res) => {
    const targetFile = req.files.myfile;

    // Rename the file to be uploaded
    const fileName = `${new Date().getTime()}-${targetFile.name}`;

    const uploadPath = __dirname + '/uploads/';
    const filePathName = uploadPath + fileName;

    targetFile.mv(filePathName, (err) => {
        if (err) {
            return res.status(500).send(err.message);
        }
        res.send('File uploaded!');
    });
});

In the example, the current timestamp is appended to the file name and then the file is uploaded.

4. Upload Only Specific Types of Files

If you want to upload only specific types of files, such as only images (png, jpg, webp), we need to check the file extension before uploading. Here is an example:

const targetFile = req.files.myfile;
const extensionName = path.extname(targetFile.name); // fetch the file extension
const allowedExtension = ['.png','.jpg','.webp'];

if(!allowedExtension.includes(extensionName)){
    return res.status(422).send("Invalid Image");
}

// File uploading code...

You have successfully set up file uploads in your Node.js application using express-fileupload. You can further enhance your application by implementing additional features such as file type validation and user authentication for secure file uploads. Thank you …

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies to ensure that we give you the best experience on our website. Privacy Policy