3

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.

SReca
  • 643
  • 3
  • 13
  • 37
  • 1
    I think it got something to do with the content-type boundary propertie, maybe this thread could help you https://stackoverflow.com/questions/3508338/what-is-the-boundary-in-multipart-form-data – Felix Fong Jul 06 '22 at 18:25
  • @SReca, Did you find any solution? – Jayna Tanawala Sep 19 '22 at 07:10
  • @JaynaTanawala sorry for the late reply. I put this project on the back burner and recently picked it up again. I've currently have a different custom setup and no longer using Multer. But I believe bodyParser may have been the cause of my issues when used globally. – SReca Apr 14 '23 at 00:50

3 Answers3

3

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!

freebishop
  • 31
  • 5
1

In my case the problem magically went away by downgrading Multer to 1.4.3.

See https://github.com/expressjs/multer/issues/1144

Lucio Crusca
  • 1,277
  • 3
  • 15
  • 41
0

What caused this too me was because I was using multiple middleware on the same route, I was using global middleware and then applied another middleware in sub route. so this caused conflits.