File Uploads Using Node.js & Express-FileUpload

In this article, we will learn about how to upload a Image with Node.js using Express-FileUpload.

Upload a File in Node.js project

Firstly, we have to install Express-FileUpload package to upload a file.

Install the express-fileupload package with  the NPM.
npm i express-fileupload

It is used for sending file.

const fileUpload = require('express-fileupload');

Write the below code in your file:

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

app.use(express.json());
app.use(fileUpload());
app.use(express.static("./public"))

app.post('/upload', async (req, res) => {
    try {
        let file = req.files.file;
        const fileName = file.name;
        const size = file.data.length;
        const extension = path.extname(fileName);

        console.log(extension)
        const allowedExtensions = /png|jpeg|jpg|gif/;

        if (!allowedExtensions.test(extension)) throw "Unsupported File";

        const md5 = file.md5;
        const URL = "/uploads" + md5 + extension;

        await util.promisify(file.mv)("./public" + URL);
        res.json({
            message: "File Uploaded",
            url: URL
        })
    } catch (error) {
        res.send(error)
    }
})

app.listen(port, () => {
    console.log(`The Port is running at ${port}`);
})

Let’s test the API:

Your Image is now Uploaded Successfully in the Upload folder.

You can Get Your Image by just clicking on a Url.

Submit a Comment

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

Subscribe

Select Categories