cheatsheets devlog projects

Setting Up File Uploads in Express

2022-11-13 1

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');
    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>

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

Now we can handle the uploaded file.'/upload', async function(req, res, next) {
    let image = req.files.image;
    let filename = './public/uploads/' +;;

We should now have file uploads fully working.