Home > database >  req.files keeps returning undefined
req.files keeps returning undefined

Time:11-04

req.files keeps returning undefined. I've tried connect-multiparty, body-parser, and express-fileupload. How do I make it work using express-fileupload and not multer?

here's my frontend:

<form action="/api/upload" method="post">
    <label for="imgHere">file:</label>
    <input type="file" id="imgHere" name="imgHere"><br><br>
    <input type="submit">
</form>

I've checked using inspect element network tab, its sending the image just fine.

here's my backend:

const express = require("express");
const app = express();
const fileUpload = require("express-fileupload")

app.use(fileUpload())

app.post('/api/upload', function(req, res) {
  console.log(req.files) // logs undefined
  res.send("uploaded.")
});

app.listen(80, function()
{
    console.log("Server loaded.")
});

How do I fix this?

CodePudding user response:

You need to specify proper enctype as form attribute as well, like this:

<form action="/api/upload" method="post" enctype="multipart/form-data">
    <label for="imgHere">file:</label>
    <input type="file" id="imgHere" name="imgHere"><br><br>
    <input type="submit">
</form>
  • Related