我在这里指定了一个非常类似的需求。
我需要有用户的浏览器手动启动下载时$('a#someID').click();
但是我不能用窗户。Href方法,因为它将当前页面内容替换为您试图下载的文件。
相反,我想在新窗口/标签中打开下载。这怎么可能呢?
我在这里指定了一个非常类似的需求。
我需要有用户的浏览器手动启动下载时$('a#someID').click();
但是我不能用窗户。Href方法,因为它将当前页面内容替换为您试图下载的文件。
相反,我想在新窗口/标签中打开下载。这怎么可能呢?
当前回答
我使用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);
最好的部分是它不会在您的服务器上留下任何残留文件,因为一切都是在运行中创建和销毁的!
其他回答
在尝试下载文件时,会发生很多小事情。浏览器之间的不一致性本身就是一场噩梦。我最终使用了这个很棒的小图书馆。 https://github.com/rndme/download
它的优点是它的灵活性,不仅url,而且客户端数据你想要下载。
文本字符串 文本dataURL 文本的团 文本数组 html字符串 html的团 ajax回调 二进制文件
对我来说,这在chrome v72测试中工作正常
function down_file(url,name){
var a = $("<a>")
.attr("href", url)
.attr("download", name)
.appendTo("body");
a[0].click();
a.remove();
}
down_file('https://www.useotools.com/uploads/nulogo[1].png','logo.png')
我很惊讶没有很多人知道元素的下载属性。请帮助传播这个消息!你可以有一个隐藏的html链接,假装点击它。如果html链接具有下载属性,它将下载文件,而不是查看文件,无论如何。这是代码。如果能找到猫的图片,它就会下载。
. getelementbyid(“下载”).click (); <a href="https://docs.google.com/uc?id=0B0jH18Lft7ypSmRjdWg1c082Y2M" download id="download" hidden></a>
注意: 并非所有浏览器都支持:http://www.w3schools.com/tags/att_a_download.asp
仅仅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>
也许只是让你的javascript打开一个只下载文件的页面,比如当你把一个下载链接拖到一个新选项卡:
Window.open("https://www.MyServer.
Org/downloads/ardiuno/WgiWho=?:8080")
打开窗口,打开一个自动关闭的下载页面。