Search code examples
node.jsmulter

Express-fileupload req.files empty


here is my app.js

 const express = require('express');
const upload = require("express-fileupload");

const app = express();
app.use(upload());
app.get("/", function(req, res){
    res.sendFile(__dirname + "/index.html");
})

app.post("/", function(req, res){
    if(req.files){
        console.log(req.files);
    }else{
        console.log("error");
    }
})


app.listen(3000, function(){
    console.log("Success");
})

and here's the index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>File upload in node js</h1>

    <form action="/" method="POST">
        <input type="file" name="file">
        <button type="submit" value="upload">upload</button>
    </form>
</body>
</html>

i get "error" from the console which means req.files is empty or does not exist i guess i don't know how to fix this, i've started using fileupload today so i'm not that familiar to that Help please


Solution

  • when submitting a file, you must use the multipart / formdata tag. see

        <form action="/" method="POST" enctype='multipart/form-data'>
            <input type="file" name="file">
            <button type="submit" value="upload">upload</button>
        </form>
    
    

    also, when making a post request with javascript, you must send it as new FormData (). see