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

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

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

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


当前回答

如果您已经在使用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');

其他回答

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

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

hitesh在2013年12月30日提交的答案实际上是有效的。只是需要一点点调整:

PHP文件可以调用自己。换句话说,只需创建一个名为saveass .php的文件,并将此代码放入其中…

        <a href="saveAs.php?file_source=YourDataFile.pdf">Download pdf here</a>

    <?php
        if (isset($_GET['file_source'])) {
            $fullPath = $_GET['file_source'];
            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;
            }
        }
    ?>

也可以使用fs-浏览器包。 它有很好的和简单的下载方法为客户端。 它是这样的:

import {downloadFile} from 'fs-browsers'; downloadFile (url-to-the-file);

function downloadURI(uri, name) 
{
    var link = document.createElement("a");
    // If you don't know the name or want to use
    // the webserver default set name = ''
    link.setAttribute('download', name);
    link.href = uri;
    document.body.appendChild(link);
    link.click();
    link.remove();
}

检查您的目标浏览器是否能够顺利运行上面的代码片段:http://caniuse.com/#feat=download

我使用FORM标签有很好的结果,因为它可以在任何地方工作,你不必在服务器上创建临时文件。方法是这样的。

在客户端(页面HTML),您可以创建这样一个不可见的表单

<form method="POST" action="/download.php" target="_blank" id="downloadForm">
    <input type="hidden" name="data" id="csv">
</form>

然后你添加Javascript代码到你的按钮:

$('#button').click(function() {
     $('#csv').val('---your data---');
     $('#downloadForm').submit();
}

在服务器端,你在download.php中有如下PHP代码:

<?php
header('Content-Type: text/csv');
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=out.csv');
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . strlen($data));

echo $_REQUEST['data'];
exit();

你甚至可以像这样创建数据的zip文件:

<?php

$file = tempnam("tmp", "zip");

$zip = new ZipArchive();
$zip->open($file, ZipArchive::OVERWRITE);
$zip->addFromString('test.csv', $_REQUEST['data']);
$zip->close();

header('Content-Type: application/zip');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="file.zip"');
readfile($file);
unlink($file); 

最好的部分是它不会在您的服务器上留下任何残留文件,因为一切都是在运行中创建和销毁的!