Unexpected end of form error when using Multer

Viewed 6400

I'm trying to upload an image (jpg/jpeg/png) from the browser to NodeJS. I have read through several tutorials and many posts on forums but very few seem to have this specific issue.

  • I've made sure to match the name provided to multer (upload.single('upload')) with the formData key (formData.append('upload', selectedFile, selectedFile.name))
  • I tried using headers originally, but later read that I should exclude them.
  • I tried submitting through a <form action="/upload" method="post" enctype="multipart/form-data"> but still got the same error.

I have found this similar question with only one answer which isn't clear Multer gives unexpetcted end of form error and this question Unexpected end of form at Multipart._final which has no answers. Every other question seems to be about an 'Unexpected field' or 'Unexpected end of multipart data' error which - judging from the solutions - is irrelevant here.

Below is my code...

Browser:

<body>
  <input type="file" id="file_uploader" name="upload" />
  <button onclick="uploadImage()" class="btn-default">SUBMIT</button>
  
  <!-- OTHER STUFF -->

</body>
<script>
  let selectedFile;
  let uploadData = new FormData();
    
  const fileInput = document.getElementById('file_uploader');
  fileInput.onchange = () => {
    selectedFile = fileInput.files[0];
    uploadData.append('upload', selectedFile, selectedFile.name);
  }

  function uploadImage(){
    fetch('/upload', {
      method: 'POST',
      body: uploadData
    }) 
    .then((response) => {
      console.log(response);
    })
    .catch((error) => {
      console.error('Error: ', error);
    });
  }
</script>

NodeJS

let express = require('express');
const multer = require('multer');

//multer options
const upload = multer({
  dest: './upload/',
  limits: {
    fileSize: 1000000,
  }
})

const app = express();

app.post('/upload', upload.single('upload'), (req, res) => {
  res.send();
}, (error, req, res, next) => {
  console.log(error.message);
})

exports.app = functions.https.onRequest(app);

...And here is the error log, if it helps:

Error: Unexpected end of form
>      at Multipart._final (C:\Users\p\Downloads\MyInvestmentHub\functions\node_modules\busboy\lib\types\multipart.js:588:17)
>      at callFinal (node:internal/streams/writable:694:27)
>      at prefinish (node:internal/streams/writable:723:7)
>      at finishMaybe (node:internal/streams/writable:733:5)
>      at Multipart.Writable.end (node:internal/streams/writable:631:5)
>      at onend (node:internal/streams/readable:693:10)
>      at processTicksAndRejections (node:internal/process/task_queues:78:11)

I haven't posted many questions as of yet, so I apologise if I'm missing something or the format is off. Let me know and I will make appropriate edits.

Thanks.

6 Answers

I also got the exact same error.

Before using multer I had installed express-fileupload. When I unistalled it using the command npm uninstall express-fileupload I could get rid of the error.

And if it is the same case with you don't forget to delete the commands you already added for express-fileupload module. (like requiring fileupload)

Hi there I ran into the same issue for me was the lack of a bodyParser middleware that allows our requests files to parsed into Buffers.

I was able to resolve the problem like so in express:

   var bodyParser = require('body-parser')

bodyParser.json([options])

In my case, the cause was other middleware. Check for other middleware running before multer. For me, the issue was express-openapi-validator middleware. Once I removed that middleware, it worked as expected.

I think this is may causes by the responsed end,so in your continuous Middleware,you can do upload file at last. i do this resolve problems.

const upload = multer({
  dest: "./uploads",
});
app.use(upload.any());
app.post(
  "/upload",
  (req, res, next) => {
    res.end("文件上传成功");
  },
  upload.single("fileKey")
);

try using these it work

const express = require('express')
const app = express()
const path = require('path')
const multer = require('multer')

var filestorageEngine = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null,'./uploads')
    },
    filename:(req,file, cb) => {
        cb(null,"[maues]-" + file.originalname)
    }
})

var upload = multer({
    storage:filestorageEngine
})

app.post('/file', upload.array('file', 3),(req, res) => {
   console.log(req.file)
    res.send("file uploaded successfully")
})

app.listen(5000, ()=> {
    console.log("server running")
})

Using body-parser package worked for me:

const bodyParser = require('body-parser')
// ...
app.use(bodyParser()) // support encoded bodies

My upload single file route:

const multer = require('multer')
const express = require('express')
const router = express()
const path = require('path') // node built-in path package

// needs "app.use(bodyParser())" middleware to work

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, process.cwd() + '/public/')
    },
    filename: function (req, file, cb) {
        // generate the public name, removing problematic characters
        const originalName = encodeURIComponent(path.parse(file.originalname).name).replace(/[^a-zA-Z0-9]/g, '')
        const timestamp = Date.now()
        const extension = path.extname(file.originalname).toLowerCase()
        cb(null, originalName + '_' + timestamp + extension)
    }
})

const upload = multer({
    storage: storage,
    limits: { fileSize: 1 * 1024 * 1024 }, // 1 Mb
    fileFilter: (req, file, callback) => {
        const acceptableExtensions = ['png', 'jpg', 'jpeg', 'jpg']
        if (!(acceptableExtensions.some(extension => 
            path.extname(file.originalname).toLowerCase() === `.${extension}`)
        )) {
            return callback(new Error(`Extension not allowed, accepted extensions are ${acceptableExtensions.join(',')}`))
        }
        callback(null, true)
    }
})

router.post('/api/upload/single', upload.single('file'), (req, res) => {
    res.status(200).json(req.file)
})

module.exports = {
    uploadRouter: router
}
Related