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

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

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

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


当前回答

使用锚标签和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");
    }

其他回答

使用一个不可见的<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'});

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

我知道我迟到了,但我想分享我的解决方案,这是上面Imagine Breaker解决方案的变化。我试着用他的方法,因为他的方法对我来说是最简单易行的。但就像其他人说的那样,它不适合某些浏览器,所以我使用jquery对它进行了一些修改。

希望这能帮助到那里的人。

function download(url) {
  var link = document.createElement("a");
  $(link).click(function(e) {
    e.preventDefault();
    window.location.href = url;
  });
  $(link).click();
}

我建议您使用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);

来自Corbacho的优秀解决方案,我只是适应了摆脱var

function downloadURL(url) {
    if( $('#idown').length ){
        $('#idown').attr('src',url);
    }else{
        $('<iframe>', { id:'idown', src:url }).hide().appendTo('body');
    }
}

也许只是让你的javascript打开一个只下载文件的页面,比如当你把一个下载链接拖到一个新选项卡:

Window.open("https://www.MyServer.
Org/downloads/ardiuno/WgiWho=?:8080")

打开窗口,打开一个自动关闭的下载页面。