我在这里指定了一个非常类似的需求。

我需要有用户的浏览器手动启动下载时$('a#someID').click();

但是我不能用窗户。Href方法,因为它将当前页面内容替换为您试图下载的文件。

相反,我想在新窗口/标签中打开下载。这怎么可能呢?


当前回答

我建议您使用mousedown事件,它被称为BEFORE the click事件。这样,浏览器就可以自然地处理点击事件,从而避免了任何奇怪的代码:

(function ($) {


    // with this solution, the browser handles the download link naturally (tested in chrome and firefox)
    $(document).ready(function () {

        var url = '/private/downloads/myfile123.pdf';
        $("a#someID").on('mousedown', function () {
            $(this).attr("href", url);
        });

    });
})(jQuery);

其他回答

使用一个不可见的<iframe>:

<iframe id="my_iframe" style="display:none;"></iframe>
<script>
function Download(url) {
    document.getElementById('my_iframe').src = url;
};
</script>

为了迫使浏览器下载它本来能够呈现的文件(例如HTML或文本文件),您需要服务器将文件的MIME Type设置为一个无意义的值,例如application/x-please-download-me或application/octet-stream,这用于任意二进制数据。

如果您只想在一个新选项卡中打开它,唯一的方法是让用户单击目标属性设置为_blank的链接。

jQuery:

$('a#someID').attr({target: '_blank', 
                    href  : 'http://localhost/directory/file.pdf'});

无论何时单击该链接,它都会在一个新的选项卡/窗口中下载文件。

使用锚标签和PHP它可以做到,检查这个答案

JQuery Ajax调用PDF文件下载

HTML
    <a href="www.example.com/download_file.php?file_source=example.pdf">Download pdf here</a>

PHP
<?php
$fullPath = $_GET['fileSource'];
if($fullPath) {
    $fsize = filesize($fullPath);
    $path_parts = pathinfo($fullPath);
    $ext = strtolower($path_parts["extension"]);
    switch ($ext) {
        case "pdf":
        header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
        header("Content-type: application/pdf"); // add here more headers for diff. extensions
        break;
        default;
        header("Content-type: application/octet-stream");
        header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
    }
    if($fsize) {//checking if file size exist
      header("Content-length: $fsize");
    }
    readfile($fullPath);
    exit;
}
?>

我正在检查文件大小,因为如果你从CDN cloudfront加载pdf,你不会得到文档的大小,这迫使文档下载为0kb,为了避免这种情况,我正在检查这种情况

 if($fsize) {//checking if file size exist
      header("Content-length: $fsize");
    }

仅仅7年之后,这里出现了一行jQuery解决方案,使用表单而不是iframe或链接:

$('<form></form>')
     .attr('action', filePath)
     .appendTo('body').submit().remove();

我已经测试过了

Chrome 55 Firefox 50 边缘IE8-10 iOS 10 (Safari/Chrome) Android浏览器

如果有人知道这个解决方案的任何缺点,我很乐意听听。


完整的演示:

<html>
<head><script src="https://code.jquery.com/jquery-1.11.3.js"></script></head>
<body>
<script>
    var filePath = window.prompt("Enter a file URL","http://jqueryui.com/resources/download/jquery-ui-1.12.1.zip");
    $('<form></form>').attr('action', filePath).appendTo('body').submit().remove();
</script>
</body>
</html>

注意:并非所有浏览器都支持。

我正在寻找一种方法,使用jquery下载文件,而不必从一开始就在href属性中设置文件url。

jQuery (< / >, { id:“downloadFile”, href:“http://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png”, 风格:“显示:隐藏。” 下载:“ }) .appendTo(身体的); $ (" # downloadFile ") [0] .click (); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本>

我建议使用下载属性而不是jQuery:

<a href="your_link" download> file_name </a>

这将下载您的文件,而不需要打开它。