Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error "Unexpected end of multipart data" in busboy file upload

I am using connect-busboy to upload file in node/express app.The problem is sometimes it works(file get uploaded succsesfully) and sometimes i get error Unexpected end of multipart data and the application crash.What could be the cause of this error? Also any help on how to debug this will be appreciated. I am using node version 5 and connect-busboy": "0.2.14"Thank you in advance

router.route('/images')    
  .post (function(req, res) {

  var fstream;
  req.busboy.on('file', function (fieldname, file, filename) {

    fstream = fs.createWriteStream(__dirname + '/public/img/'+ filename);
    file.pipe(fstream);
    file.on('end', function() {
      console.log('File [' + fieldname + '] Finished sucessfully');
     });
    fstream.on('error',function(err){
      console.log('fstream error' + err);
      file.unpipe();
    });
    fstream.on('close', function () {
      res.status(200);
      res.json({ message: 'File uploaded' });

    });
  });
  req.pipe(req.busboy);

});

This is the error i am getting

throw er; // Unhandled 'error' event
: Error: Unexpected end of multipart data
2017-05-07T20:28:27.599826+00:00 app[web.1]:     at 
/app/node_modules/busboy/node_modules/dicer/lib/Dicer.js:62:28
like image 604
sparks Avatar asked May 11 '17 02:05

sparks


2 Answers

For me, I received this error when I used \n newlines instead of \r\n newlines when formatting my post body on the client side.

When I fixed the newlines (as seen in code below) it worked.

fetch('/api/upload', 
  { method: 'POST',
    credentials: 'include',
    headers: {'Content-type': 'multipart/form-data; boundary=XXX' },
    body: '--XXX\r\nContent-Disposition: form-data; name="file"; filename="filename.csv"\r\nContent-Type: text/csv\r\n\r\nA,B,C\r\n1,1.1,name1\r\n2,2.2,name2\r\n\r\n--XXX--'
  });
like image 185
Doug Coburn Avatar answered Nov 13 '22 17:11

Doug Coburn


If anybody else is having an issue with this still, my issue was something on the front end. Using Swift, it seems like there was an issue if you use the default URLSession config. I changed it from:

let session = URLSession(configuration: .default, delegate: self, delegateQueue: nil)

to the following:

  let sessionConfig = URLSessionConfiguration.background(withIdentifier: "it.yourapp.upload")
        sessionConfig.isDiscretionary = false
        sessionConfig.networkServiceType = .default

        let session = URLSession(configuration: sessionConfig, delegate: self, delegateQueue: OperationQueue.main)

and now it works great!

like image 1
jusynth Avatar answered Nov 13 '22 15:11

jusynth