Search code examples
javascripthtmlnode.jsmulter

undefuned req.file in multer using form html


i have a form on my upload page and the code is like this:

<div>
        <h1>welcome to HOMETUBE</h1>
        <form action="/post" method="post">
            <input type="file" name='static/Files' id="Files">
            <input type="submit" value="Submit">
        </form>
    </div>

and here is my server.js :

const express = require("express");
const f = require("fs");
const multer = require("multer");
const cors = require('cors');

const fileStorage = multer.diskStorage({
    destination:(req,file,cb) =>{
        cb(null,'./static/Files')
    },

    filename:(req,file,cb)=>{
        cb(null,file.originalname)
    }
})
const upload = multer({storage : fileStorage})

indexPage = f.readFileSync("./index.html");
postPage = f.readFileSync("./post.html");

const app = express();
app.use(cors());
app.use("/",express.static("static/css"))
app.get("/",(req,res)=>{
    res.end(indexPage);
})

app.get('*', (req, res) => {
    res.status(404).send(`<h1>${req.url} was not found!</h1>`);
})

app.post("/post",upload.array('static/Files',100),(req,res)=>{
    console.log(req.files);
    res.end(postPage);
})

app.listen(1010,()=>{
})

and the files system:

this

now the problem is that when every i try to select a file and then post it by clicking the submit button is just console logs undefined but when i tried with postman it works just as it is supposed to work what can be the problem here ????


Solution

  • i got it , i needed

    enctype="multipart/form-data"

    <form action="/post" method="post" enctype="multipart/form-data">
                <input type="file" name='static/Files' id="Files">
                <input type="submit" value="Submit">
            </form>
    

    instead of

    <form action="/post" method="post" >
                <input type="file" name='static/Files' id="Files">
                <input type="submit" value="Submit">
            </form>