简体   繁体   English

如何通过javascript下载pdf文件?

[英]How to download a pdf file through javascript?

My javascript code makes the following AJAX request to my node.js server: 我的JavaScript代码向我的node.js服务器发出以下AJAX请求:

var url = '/node/download';
var downloadRequest = new goog.net.XhrIo();
downloadRequest.headers.set('content-type', 'application/json');
downloadRequest.send(url);

My node.js server creates a pdf at the node and streams the pdf back to the client via the following code: 我的node.js服务器在节点上创建一个pdf,并通过以下代码将pdf流回客户端:

    var filestream = fs.createReadStream(pdfpath);                  
    res.writeHead(200, {
        'Content-disposition': 'attachment; filename=' + filename,
        "Content-Type":"application/pdf","Content-Transfer-Encoding": "binary"});
    filestream.on('data', function(chunk) {                     
        res.write(chunk);
    });
    filestream.on('end', function() {
        res.end();
    });

But now I am having trouble at how to receive this response back at the javascript client so that a download prompt will open to allow the user to download and save the pdf file. 但是,现在我在如何在javascript客户端处接收此响应方面遇到了麻烦,因此将打开一个下载提示,以允许用户下载并保存pdf文件。

Please help! 请帮忙!

Thanx in advance! 提前感谢!

PS Plz also suggest any better way to implement my node's code(if there is any) PS Plz还建议了任何更好的方法来实现我节点的代码(如果有的话)

Edit: One possible solution would be to send my request like this: 编辑:一种可能的解决方案是像这样发送我的请求:

window.location.assign('/node/download');

This way i get the download prompt and everything works fine except that the asynchronous nature of the product is sacrificed. 这样,我得到了下载提示,并且一切正常,除了牺牲了产品的异步特性。 Is there a work around for this so that I can also retain asynchronicity? 是否有解决方法,这样我也可以保持异步性?

For downloading a pdf file saved on the server 用于下载保存在服务器上的pdf文件

Make the request like this from the client javascript: 从客户端javascript发出这样的请求:

var reqObj = new XMLHttpRequest();
reqObj.open('GET','getpdf',true);     // 'getpdf' is the URI to recongize your request at the server
reqObj.send();

reqObj.onreadystatechange = function() {
    var resObj = this;
    if(resObj.readyState == resObj.DONE) {
        if (resObj.status != 200) {
            console.log("pdf can't be downloaded");
        } else if (resObj.status == 200){
            var resTxt = reqObj.responseText;
            window.location.assign(resTxt);    // Opens the pdf download prompt
        }
    }
}

At the node handle the request received from above and respond: 在节点处处理从上方收到的请求并做出响应:

var http = require('http');

function getPDFUrl() {
    return "http://testing.com/pdf/test.pdf";
}

var handler = http.createServer(function(request, response) {
if (request.url == 'getpdf' && request.method.toLowerCase() == 'get') {
    var pdfUrl = getPDFUrl();       //get pdf url here

    if (pdfUrl != null && pdfUrl != undefined && pdfUrl != '') {
        response.writeHead(200, {"Content-Type":"text/html"});
        response.write(pdfUrl);
        response.end();
    } else {
        response.writeHead(404, {"Content-Type":"text/html"});
        response.write("Not Found");
        response.end();
    }

}
});

I implement similar async file generation features in some apps. 我在某些应用程序中实现了类似的异步文件生成功能。 The approach I take is a little more involved, but keeps your interface async. 我采用的方法要复杂一些,但可以保持界面异步。

  • Client sends a request for the file to be generated. 客户端发送要生成的文件的请求。
  • Server sends response with the URL for the generated file. 服务器发送带有生成文件URL的响应。
  • Client makes a second request to download the generated file. 客户端再次请求下载生成的文件。

This is invisible to the user, they will just need to wait for the second transaction to come back. 这对于用户是不可见的,他们只需要等待第二笔交易回来即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM