Force download a pdf link using javascript/ajax/jquery

前端 未结 7 2015
夕颜
夕颜 2020-11-27 04:51

suppose we have a pdf link \"http://manuals.info.apple.com/en/iphone_user_guide.pdf\"(just for example and to let u know that file is not on my server, i only have the link)

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 05:25

    Using Javascript you can download like this in a simple method

    var oReq = new XMLHttpRequest();
    // The Endpoint of your server 
    var URLToPDF = "https://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf";
    // Configure XMLHttpRequest
    oReq.open("GET", URLToPDF, true);
    
    // Important to use the blob response type
    oReq.responseType = "blob";
    
    // When the file request finishes
    // Is up to you, the configuration for error events etc.
    oReq.onload = function() {
    // Once the file is downloaded, open a new window with the PDF
    // Remember to allow the POP-UPS in your browser
    var file = new Blob([oReq.response], { 
        type: 'application/pdf' 
    });
    
    // Generate file download directly in the browser !
    saveAs(file, "mypdffilename.pdf");
    };
    
    oReq.send();
    

提交回复
热议问题