从node.js中的webservice下载.pdf文件 [英] Download a .pdf file from a webservice in node.js
问题描述
浏览器直接访问外部Web服务,将用户带到网页,根据网址传递的参数处理请求,然后直接在浏览器视图中返回pdf文件。
我正在开发一个应用程序,旨在调用此Web服务并将生成的.pdf文件返回给用户。
我尝试了什么:
为了得到这个,我尝试使用请求npm包,如下所示:
There's an external webservice accessed directly by browser that takes the user to a web page which deals the request according to the parameters passed in the url and then returns a pdf file directly in the browser view.
I'm working on an application that aims to make a call to this webservice and return a generated .pdf file to the user.
What I have tried:
To get this I tried to use the request npm package as follows:
var request = Meteor.npmRequire ( 'request');
request.GET ({
url: this_nfse.link_nfse, timeout: 1500 jar: true,
encoding: 'binary'
}
, Meteor.bindEnvironment (function (error, response, body) {
if (!error && response)
{
// Handle result according to the application purpose
}
}));
但我得到的身体对象是处理pdf文件请求时负责的html页面,而不是文件或其自身的表示。
我是nodejs / meteor的初学者,任何欢迎提供帮助。
But the body object that I get is the html page that is reponsible in deal with the pdf file request, not the file or representation of itself.
I'm a beginner in nodejs/meteor, and any help will welcome.
推荐答案
你可以试试。我已经为此工作了。这个例子对你有帮助。
You can try. I have already worked for this. This example will help you.
var path = require('path');
var mime = require('mime');
app.get('/download', function(req, res){
var file = __dirname + '/upload-folder/dramaticpenguin.MOV';
var filename = path.basename(file);
var mimetype = mime.lookup(file);
res.setHeader('Content-disposition', 'attachment; filename=' + filename);
res.setHeader('Content-type', mimetype);
var filestream = fs.createReadStream(file);
filestream.pipe(res);
});file);
filestream.pipe(res);
});
如果你想将文件发送到前端以获取句柄,然后您可以尝试:
If you want to send the file to front end for handle then you can try :
exports.sendPdf = function(req, res) {
var donneRecu = req.body;
console.log(donneRecu['lien']);
var url = donneRecu['lien']; //pdf link
http.get(url, function(response) {
var chunks = [];
response.on('data', function(chunk) {
console.log('downloading');
chunks.push(chunk);
});
response.on("end", function() {
console.log('downloaded');
var jsfile = new Buffer.concat(chunks).toString('base64');
console.log('converted to base64');
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header('content-type', 'application/pdf');
res.send(jsfile);
});
}).on("error", function() {
callback(null);
});
}
这篇关于从node.js中的webservice下载.pdf文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!