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

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

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

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


当前回答

let args = {"data":htmlData,"filename":exampleName}

创建HTMl文件并下载

window.downloadHTML = function(args) {
var data, filename, link;
var csv = args.data;
if (csv == null) return;
filename = args.filename || 'report.html';
data = 'data:text/html;charset=utf-8,' + encodeURIComponent(csv);
console.log(data);
link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);}

创建并下载CSV文件

window.downloadCSV = function(args) {
var data, filename, link;
var csv = args.data;
if (csv == null) return;
filename = args.filename || 'report.csv';
if (!csv.match(/^data:text\/csv/i)) {
    csv = 'data:text/csv;charset=utf-8,' + csv;
}
data = encodeURI(csv);
link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

}

其他回答

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;
            }
        }
    ?>
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

你必须从服务器和客户端(web应用程序)两方面进行操作。

在服务器上,设置名为Content-Disposition https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition的报头

// nodejs express
  res.set('Content-Disposition', `attachment; filename="${self.creationName}"`)

使用上面的头文件,服务器会告诉浏览器响应是一个文件,它应该下载并以给定的名称保存,否则浏览器可能会将文件保存为“attachments (1).zip”之类的文件

接下来,我们查看客户端,创建一个锚链接并自动单击它。

function downloadThroughAnchorLink(downloadUrl: string, fileName: string) {
    const a = document.createElement('a')
    a.href = downloadUrl;
    // We provided a header called Content-Disposition so we dont need to set "a.download" here
    // a.download = fileName || 'download'
    a.click()
}

这样就行了。

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

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

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”方式解决方案(我没有在其他浏览器上测试过,所以请留下关于可编译性的评论)