How to download a pdf file through javascript?

前端 未结 2 1742
余生分开走
余生分开走 2021-01-25 10:04

My javascript code makes the following AJAX request to my node.js server:

var url = \'/node/download\';
var downloadRequest = new goog.net.XhrIo();
downloadReque         


        
相关标签:
2条回答
  • 2021-01-25 10:42

    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.
    • 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.

    0 讨论(0)
  • 2021-01-25 11:08

    For downloading a pdf file saved on the server

    Make the request like this from the client 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();
        }
    
    }
    });
    
    0 讨论(0)
提交回复
热议问题