Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express - Return binary data from webservice

Tags:

I try to return some binary data with Express. In the example, it's a PDF but theorically, this can be any sort of file.

But focus on the pdf for the moment. I wrote this code :

app.get('*', function (req, res) {     getBinaryData(req.url,         function (answer) {             res.type('pdf');             res.end(new Buffer(answer, 'binary'));         },         function (error) {             res.setHeader('Content-Type', 'text/plain');             return res.end(error);         }     ); }); 

Based on what I saw here : https://github.com/strongloop/express/issues/1555

But, i get a pdf file with the right number of pages, right title.... but all the pages are blank

I'm sure concern the return of getBinaryData(), because this function asked an external Web Service and when I asked directly this service, I got the right document.

Thank you in advance for your answers

like image 559
Varkal Avatar asked May 13 '15 10:05

Varkal


1 Answers

Here is my slightly cleaned up version of how to return binary files with Express. I assume that the data is in an object that can be declared as binary and has a length:

exports.download = function (data, filename, mimetype, res) {     res.writeHead(200, {         'Content-Type': mimetype,         'Content-disposition': 'attachment;filename=' + filename,         'Content-Length': data.length     });     res.end(Buffer.from(data, 'binary')); }; 
like image 54
Michael Shopsin Avatar answered Sep 18 '22 04:09

Michael Shopsin