Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
808 views
in Technique[技术] by (71.8m points)

node.js - Express - Return binary data from webservice

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'));
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...