Search code examples
javascriptnode.jsexpressmulter

picture "undefined" with multer


im trying to get a picture uploaded using multer, here is my server side

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads/')
    },
    filename: function (req, file, cb) {
        cb(null, `${file.originalname}`)
    }
})


const upload = multer({storage: storage});

app.post('/upload', upload.single("pic"), function (req, res) {
    console.log(req.file)
    res.send('File uploaded!')
})

in my post method my req.file is undefined

this is my client side

<form action="/upload" method="post">
                    <input type="file" id="files" style="visibility: hidden;" name = "pic" accept="image/*">
                    <br>
                    <label for="files" id="files" class = "lbl">Select file</label>
                    <br>
                    <br>
                    <input type="submit" value="Upload" name="submit" id = "submit">
                </form>

if anyone can send a solution it would be amazing. thanks you.


Solution

  • I found that multer().single(...) fills req.file only if the content type is multipart/form-data:

    <form action="/upload" method="post" enctype="multipart/form-data">