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

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

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

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


当前回答

如果您不需要浏览另一个页面,这可能会很有帮助。 这是一个基本的javascript函数,所以可以用在任何平台的后端是javascript

window.location.assign('any url or file path')

其他回答

适用于Chrome, Firefox和IE8及以上。

var link=document.createElement('a');
document.body.appendChild(link);
link.href=url ;
link.click();

如果您已经在使用jQuery,可以利用它生成一个较小的代码片段 jQuery版本的Andrew的回答:

var $idown;  // Keep it outside of the function, so it's initialized once.
downloadURL : function(url) {
  if ($idown) {
    $idown.attr('src',url);
  } else {
    $idown = $('<iframe>', { id:'idown', src:url }).hide().appendTo('body');
  }
},
//... How to use it:
downloadURL('http://whatever.com/file.pdf');

Firefox和Chrome测试:

var link = document.createElement('a');
link.download = 'fileName.ext'
link.href = 'http://down.serv/file.ext';

// Because firefox not executing the .click() well
// We need to create mouse event initialization.
var clickEvent = document.createEvent("MouseEvent");
clickEvent.initEvent("click", true, true);

link.dispatchEvent(clickEvent);

这实际上是firefox的“chrome”方式解决方案(我没有在其他浏览器上测试过,所以请留下关于可编译性的评论)

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

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

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

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