Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multipart/form-data request failed. Stream ended unexpectedly

I'm sending data from a nodejs application to a spring rest endpoint. I followed the example on form-data to fs.createReadStream from a file, and that's fine. But since my application generates this data, what I actually need is to send the data that's stored in a variable (as a string). So I followed this answer to create a stream from a string, but on the Java end I receive a "stream ended unexpectedly" error.

var form = new FormData();
form.append('id', id);

// this works
//form.append('inputFiles[]', fs.createReadStream('test.xml'));

//this does not
const Readable = require('stream').Readable;
let s = new Readable();
s._read = () => {};
s.push('some data generated by my application');
s.push(null);

form.append('inputFiles[]', s);

form.submit(url, function(error, result) {
  if (error) {
    console.log('Error!');
  }
});

Do I need to pipe this data somehow? Or specify content length (if so, how do I determine the length?) I tried to add { filename : 'test.xml', contentType: 'application/xml' } to the readable to maybe mimic the file, but still get the same error.

like image 688
otgw Avatar asked Dec 03 '25 15:12

otgw


1 Answers

In case anyone else runs into the same issue -- I needed to have all 3 of the extra fields, including knownLength

    let stream = new Readable();
    stream.push(foo);
    stream.push(null);
    form.append('inputFiles[]', stream, {
      filename : 'test.xml',
      contentType: 'application/xml',
      knownLength: foo.length
    }); //extra fields necessary
like image 154
otgw Avatar answered Dec 05 '25 11:12

otgw



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!