Express - Return binary data from webservice

后端 未结 2 1360
礼貌的吻别
礼貌的吻别 2020-12-16 12:50

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 wrot

相关标签:
2条回答
  • 2020-12-16 13:32

    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'));
    };
    
    0 讨论(0)
  • 2020-12-16 13:47

    I found a more simple solution :

    request(req.url).pipe(res);
    

    This pipes the original response from distant Web Service directly to my response! I got the correct file regardless of the file type.

    0 讨论(0)
提交回复
热议问题