Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve Multer Error: Unexpected end of form?

I found other similar questions regarding Multer, but with no answers. I'm trying to upload a file with next.js (front-end) and node.js (back-end). The data is being posted via the network tab when using dev tools.

Below is my setup:

app.js

const express = require('express');
const bodyParser = require('body-parser');

// Get routes
const routeUser = require('./routes/user');

// Create an express server
var app = express();

// Add necessary middleware
app.use(bodyParser.urlencoded({ extended: true })); // Support encoded bodies
app.use(bodyParser.json({
  type: ["application/x-www-form-urlencoded", "application/json"], // Support json encoded bodies
}));

// Custom routes
routeUser(app);

// Start server on port 1234
app.listen(1234, () => {
  console.log("API is running.");
});

route/user.js

const multer = require('multer');

module.exports = function(app) {

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

  app.post('/user/update', upload.single('user_photo'), (req, res) => {

    console.log(req.body, req.file);

  });
}

Form

submit(event) {
  event.preventDefault();
  let form_values = new FormData(event.target);
  fetch(this.props.env.api + "/user/update", {
    method: 'post',
    headers: {
      'Content-Type': 'multipart/form-data; boundary=MyBoundary',
    },
    body: form_values
  }).then((response) => {
    return response.json();
  }).then((response) => {
    console.log(response);
  });
}

------

<form onSubmit={this.submit}>
  <input type="file" name="user_photo"/>
  <button type="submit">Upload</button>
</form>

I've tried several tutorials, I'm setting it up according to the docs, yet I keep getting the following error:

Error: Unexpected end of form
    at Multipart._final (...\node_modules\busboy\lib\types\multipart.js:588:17)

If I remove multipart/form-data as Content-Type, the form submits with no problem, but with no file. My guess it has something to do with the way the formData object is being received.

like image 985
SReca Avatar asked Oct 26 '25 12:10

SReca


1 Answers

Hey @SReca, just faced this issue today and hope I can help you out here and anybody else reading this.

Resolving Unexpected end of form

Regarding the original issue about Unexpected end of form, you are correct in removing the Content-Type as a solution. This is because sending FormData() with regular Fetch or XMLHttpRequest will automatically have the header set by the Browser. The Browser will also attach the boundary needed in all multipart/form-data requests in order indicate when a form starts and ends. More details can be found on MDN's docs about Using FormData Objects... there's a warning about explicitly setting Content-Type.

Potential fix for missing file

Now, about the missing file, it's possible that it has an incorrect reference to the path you're expecting. I am not using diskStorage, but I am using regular dest option to save my file and had the same problem (wanted to save images to ./assets/images). What worked for me was to supply the complete directory path. Maybe changing your callback function in the destination property to

// Assuming the the path module is 'required' or 'imported' beforehand
cb(null, path.resolve(__dirname, '<path-to-desired-folder>'));

will solve the issue. Hope this helps!

like image 104
freebishop Avatar answered Oct 29 '25 02:10

freebishop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!