Save images from file input in form POST method

So recently I've been learning express JS and wanted to do a simple project of making a website with a form. it will receive a name and an image. Show both after submitting the form.

The problem lies in the file input in the form. I can grab the name of the file but I don't know how to download it and save it in an assets/gallery folder to later show it. Can anyone help? Thanks

Below is the index.js code and also for added context I use hard coded array called gallery to store the data since I wanted to just focus on express and not deal with database for now.

// index.js file
const express = require('express');
const path = require('path');
const gallery = require('./Gallery');

const app = express();
const PORT = process.env.PORT || 3000;


app.use(express.static(path.join(__dirname)));
app.set('view engine', 'ejs');

app.use(express.json());
app.use(express.urlencoded({extended: false}));

app.get("/", (req, res) => res.render("mini-gallery", {
    title: "Gallery Photos",
    gallery,
    dir: path.join("assets", "gallery")
}));

app.post("/", (req, res) => {
    //Grab name and image url
    const newImage = {
        name: req.body.name,
        imageUrl: req.body.image
    }

    if(!newImage.name || !newImage.imageUrl){
        res.status(404).json({msg:"Please insert the form accordingly"});
    }
   
    gallery.push(newImage);
    res.redirect("/");
})

app.listen(PORT, () => {
    console.log(`Server started at port ${PORT}`);
});
Was this page helpful?