Monday | 04 NOV 2024
[ previous ]
[ next ]

Setting Up File Uploads in Express

Title:
Date: 2022-11-13
Tags:  

A very useful library to upload files and make them easily accessible in an express project.

First install express-fileupload

npm install express-fileupload

Update app.js to use this middleware.

var fileUpload = require('express-fileupload');
app.use(fileUpload({
    createParentPath: true
}));

The createParentPath flag makes sure the upload path is created when the mv command is used.

At this point, the request will now carry a new array called files. Inside our routes we can now do req.files to get the upload files.

<form method="POST" action="/upload" enctype="multipart/form-data">
    <label for="image">Image:</label>
    <input type="file" id="image" name="image">
    <button type="submit"></button>
</form>

The important attribute here is the enctype to make sure files get uploaded.

Now we can handle the uploaded file.

router.post('/upload', async function(req, res, next) {
    let image = req.files.image;
    let filename = './public/uploads/' + image.name;
    image.mv(filename);
    res.send("Uploaded.");
});

We should now have file uploads fully working.