Reputation: 883
I've the following scenario: to return a multipart/mixed response that will contain the following items using NodeJS, where we control both ends of the communication so we should be able to eliminate interoperability issues.
--whoop Content-Disposition: attachment; name="zip"; filename="tobi.zip" Content-Type: application/zip ... data here ... --whoop Content-Disposition: form-data; name="name" Content-Type: text/plain Tobi --whoop--
I need to stream this back to the user so that they can process the JSON file and if required, expand out the specific ZIP file they are interested in.
From looking at the API guide http://expressjs.com/api.html I dont see how this is possible? I've got single ZIP files being returned correctly but need to support this business scenario.
I'm trying to create something similar to the following: HTTP multipart response using Perl or PHP
The res should contain a JSON file and all the associated ZIP's.
Any help is appreciated. Thanks.
J
Upvotes: 1
Views: 4955
Reputation: 883
Solution looks like this - called per item that needs to be written to the response.
res.writeHead(200, {
'Content-Type': 'multipart/x-mixed-replace; charset=UTF-8; boundary="' + SNAPSHOT_BOUNDARY + '"',
Connection: 'keep-alive',
Expires: 'Fri, 01 Jan 1990 00:00:00 GMT',
'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate',
Pragma: 'no-cache'
});
feed.snapshots.forEach(function (item) {
writeResponse(item);
});
function writeResponse(item) {
var buffer = new Buffer(0);
var readStream = getGridFs().createReadStream({root: 'items', _id: snapshotItem._id});
readStream.on('error', function (err) {
if (err) {
// handle error
}
});
readStream.on('data', function (chunk) {
buffer = Buffer.concat([buffer, chunk]);
});
readStream.on('end', function () {
res.write('\n\n' + SNAPSHOT_BOUNDARY + '\n');
res.write('Content-Disposition: filename="' + item.filename + '" \n');
res.write('Content-Type: application/zip \n');
res.write('Content-length: ' + buffer.length + '\n\n');
res.write(buffer);
});
}
Still having issues with supertest parsing multipart responses - ticket open at https://github.com/felixge/node-formidable/issues/348
Upvotes: 2