我想使用远程方法从第三方API下载pdf文件,我的实现是:
Staff.statement = async (id, year, month) => {
const fileData = await ThirdPartyAPI.restGET(id, year, month);
const filename = `Statement_${month}${year}.pdf`;
return [fileData, 'application/pdf', `inline;filename=${filename}`];
};
Staff.remoteMethod('statement ', {
accepts: [
{ arg: 'id', type: 'any', required: true },
{ arg: 'year', type: 'string', required: true },
{ arg: 'month', type: 'string', required: true }
],
description: 'Download statement file',
http: { path: '/:id/statement', verb: 'GET' },
returns: [
{ arg: 'body', type: 'file', root: true },
{ arg: 'Content-Type', type: 'string', http: { target: 'header' } },
{ arg: 'Content-Disposition', type: 'string', http: { target: 'header' } }
});
问题是该文件可以正确查看/下载(如果我设置了Content-Disposition: attachment;filename=${filename}
),但它是一个空白的pdf:
我从招摇中检查了响应数据,该数据与我直接从第三方API获得的数据相同:
这是响应头:
{
"strict-transport-security": "max-age=0; includeSubDomains",
"content-encoding": "",
"x-content-type-options": "nosniff",
"date": "Mon, 16 Jul 2018 04:50:36 GMT",
"x-download-options": "noopen",
"x-frame-options": "SAMEORIGIN",
"content-type": "application/pdf",
"transfer-encoding": "chunked",
"content-disposition": "inline;filename=Statement_062016.pdf",
"connection": "keep-alive",
"access-control-allow-credentials": "true",
"vary": "Origin",
"x-xss-protection": "1; mode=block"
}
显示或数据出了什么问题?
更新:在穆罕默德·拉希姆(Mohammad Raheem)的帮助下,我的实现
Staff.statement = (id, year, month, res, cb) => {
const options = {
url: // {{request_url}},
headers: {
authorization: // {{token}}
}
};
request(options)
.on('error', err => cb(err))
.on('response', response => cb(null, response, 'application/pdf'))
.pipe(res);
// using 'request-promise' package:
// request(options)
// .then(response => cb(null, response, 'application/pdf'))
// .catch(err => cb(err));
};
};
Staff.remoteMethod('statement ', {
accepts: [
{ arg: 'id', type: 'any', required: true },
{ arg: 'year', type: 'string', required: true },
{ arg: 'month', type: 'string', required: true },
{ arg: 'res', type: 'object', http: { source: 'res' } }
],
description: 'Download statement file',
http: { path: '/:id/statement', verb: 'GET' },
returns: [
{ arg: 'body', type: 'file', root: true },
{ arg: 'Content-Type', type: 'string', http: { target: 'header' } }
});
答案 0 :(得分:2)
您可以在此处检查我是否下载了pdf文件的示例代码
var request = require('request');
var fs = require("fs");
var _downloadPdf = function (url,callback) {
var url = 'your-url';
var options = {
method: 'GET',
url: url,
headers: {
'Content-Type': 'application/pdf',
}
};
var _filepath = 'D://Node/upload/temp/sample.pdf';
//If you want to go with pipe in case of chunk data
var dest = fs.createWriteStream(filepath);
request(options, function (error, response, body) {
if (error)
throw new Error(error);
}).on('end', function () {
return callback(filepath);
}).on('error', function (err) {
return callback(err);
}).pipe(dest);
}