简体   繁体   English

使用 javascript/ajax/jquery 强制下载 pdf 链接

[英]Force download a pdf link using javascript/ajax/jquery

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)...now i have to provide a button on my site that will download the file.假设我们有一个 pdf 链接“ http://manuals.info.apple.com/en/iphone_user_guide.pdf ”(只是为了让你知道该文件不在我的服务器上,我只有链接).. .现在我必须在我的网站上提供一个按钮来下载文件。

i have tried various things like window.open, href etc. methods but it open the link on other window.我尝试了各种方法,例如 window.open、href 等方法,但它会在其他窗口上打开链接。 i know thats because now all browser comes with a adobe plugin which opens it in another window, but still isnt there any way i give the user the option of download rather than opening it, through client side scripting ..我知道那是因为现在所有浏览器都带有一个 adobe 插件,可以在另一个窗口中打开它,但是我仍然没有任何方法可以通过客户端脚本为用户提供下载而不是打开它的选项..

plz help.. thanks请帮助..谢谢

Here is a Javascript solution (for folks like me who were looking for an answer to the title):这是一个Javascript解决方案(适用于像我这样正在寻找标题答案的人):

function SaveToDisk(fileURL, fileName) {
    // for non-IE
    if (!window.ActiveXObject) {
        var save = document.createElement('a');
        save.href = fileURL;
        save.target = '_blank';
        save.download = fileName || 'unknown';

        var evt = new MouseEvent('click', {
            'view': window,
            'bubbles': true,
            'cancelable': false
        });
        save.dispatchEvent(evt);

        (window.URL || window.webkitURL).revokeObjectURL(save.href);
    }

    // for IE < 11
    else if ( !! window.ActiveXObject && document.execCommand)     {
        var _window = window.open(fileURL, '_blank');
        _window.document.close();
        _window.document.execCommand('SaveAs', true, fileName || fileURL)
        _window.close();
    }
}

source: http://muaz-khan.blogspot.fr/2012/10/save-files-on-disk-using-javascript-or.html来源: http : //muaz-khan.blogspot.fr/2012/10/save-files-on-disk-using-javascript-or.html

Unfortunately this is not working for me with IE11, which is not accepting new MouseEvent.不幸的是,这不适用于 IE11,IE11 不接受新的 MouseEvent。 I use the following in that case:在这种情况下,我使用以下内容:

//...
try {
    var evt = new MouseEvent(...);
} catch (e) {
    window.open(fileURL, fileName);
}
//...

Use the HTML5 "download" attribute使用 HTML5“下载”属性

<a href="iphone_user_guide.pdf" download="iPhone User's Guide.PDF">click me</a>

2021 Update: Now supported in all major browsers! 2021 年更新:现在所有主要浏览器都支持! see: caniuse.com/#search=download请参阅: caniuse.com/#search=download

If you need to support older browsers, or you're looking for an actual javascript solution (for some reason) please see lajarre's answer如果您需要支持旧浏览器,或者您正在寻找实际的javascript 解决方案(出于某种原因),请参阅lajarre 的答案

With JavaScript it is very difficult if not impossible(?).使用 JavaScript 是非常困难的,如果不是不可能的话(?)。 I would suggest using some sort of code-behind language such as PHP, C#, or Java.我建议使用某种代码隐藏语言,例如 PHP、C# 或 Java。 If you were to use PHP, you could, in the page your button posts to, do something like this:如果您要使用 PHP,您可以在按钮发布到的页面中执行以下操作:

<?php
header('Content-type: application/pdf');
header('Content-disposition: attachment; filename=filename.pdf');
readfile("http://manuals.info.apple.com/en/iphone_user_guide.pdf");
?>

This also seems to work for JS (from http://www.phpbuilder.com/board/showthread.php?t=10149735 ):这似乎也适用于 JS(来自http://www.phpbuilder.com/board/showthread.php?t=10149735 ):

<body>
<script>
function downloadme(x){
myTempWindow = window.open(x,'','left=10000,screenX=10000');
myTempWindow.document.execCommand('SaveAs','null','download.pdf');
myTempWindow.close();
}
</script>

<a href=javascript:downloadme('http://manuals.info.apple.com/en/iphone_user_guide.pdf');>Download this pdf</a>
</body>

Here is the perfect example of downloading a file using javaScript. 是使用 javaScript 下载文件的完美示例。

Usage: download_file(fileURL, fileName);用法: download_file(fileURL, fileName);

If htaccess is an option this will make all PDF links download instead of opening in browser如果 htaccess 是一个选项,这将使所有 PDF 链接下载而不是在浏览器中打开

<FilesMatch "\.(?i:pdf)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>

Using Javascript you can download like this in a simple method使用Javascript,您可以通过简单的方法像这样下载

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();

Any working methods ?有什么工作方法吗? I need to download the pdf files while inside of an offline page (with chrome) so sadly cant use php or htaccecs or chrome manual options我需要在离线页面(使用 chrome)中下载 pdf 文件,所以很遗憾不能使用 php 或 htaccecs 或 chrome 手动选项

In javascript use the preventDefault() method of the event args parameter.在 javascript 中使用 event args 参数的 preventDefault() 方法。

<a href="no-script.html">Download now!</a>

$('a').click(function(e) {
    e.preventDefault(); // stop the browser from following
    window.location.href = 'downloads/file.pdf';
});

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

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