node.jsexpressfile-uploadpostmanmulter

Why do I get this error: Postman Error: Malformed part header?


I am using Postman with these headers.

enter image description here

If I keep the default Content-Type, it will throw me the error

Error: Malformed part header

However, if I remove the default Content-Type and put in my own (see the last key), it will NOT be able to scan my uploaded file (req.file is undefined). If I have any sort of boundary, the same error is thrown.

Thus, I am leaning towards thinking that the boundary is the problem. However, if I remove it, I won't be able to see my req.file

Here is my node.js code

const multer = require("multer")

const upload = multer({
    storage: multer.diskStorage({
        destination: (req, file, callback) => {
            callback(null, "./images")
        },
        filename: (req, file, callback) => {
            callback(null, file.originalname)
        }
    })
})

app.post("/single", upload.single("upload"), (req, res) => {
    console.log(req.file);
    res.send("Testing123")
})

UPDATE: I have not found the answer yet, but when i closed and reopened postman, the Error: Malformed part header No longer shows. However, my req.file is still undefined

and because someone asked if another stack overflow question answered my question: nope, it didn't, and here is why. I am already doing Answer 1 Answer 1 , the checked answer

Answer 3 (multipart/mixed) also makes my req.file undefined

I watched the video from Answer 4 but it's the same as answer one


Solution

  • The answer was pretty stupid. For some reason, it doesn't show req.file, BUT it still processes all the same. It really confused me, but I changed my code to the official multer error handling way, https://www.npmjs.com/package/multer#error-handling

    app.post('/profile', function (req, res) {
      upload(req, res, function (err) {
        if (err instanceof multer.MulterError) {
          // A Multer error occurred when uploading.
        } else if (err) {
          // An unknown error occurred when uploading.
        } else {
        // Everything went fine.
          console.log(req.file)
        }
    
      })
    })
    

    i would be able to see it under //Everything went fine portion. It's a bit weird, so if anyone knows the reason why, please tell me