Issue
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.
Solution
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
Answered By - otgw