我在这里指定了一个非常类似的需求。
我需要有用户的浏览器手动启动下载时$('a#someID').click();
但是我不能用窗户。Href方法,因为它将当前页面内容替换为您试图下载的文件。
相反,我想在新窗口/标签中打开下载。这怎么可能呢?
我在这里指定了一个非常类似的需求。
我需要有用户的浏览器手动启动下载时$('a#someID').click();
但是我不能用窗户。Href方法,因为它将当前页面内容替换为您试图下载的文件。
相反,我想在新窗口/标签中打开下载。这怎么可能呢?
当前回答
在尝试下载文件时,会发生很多小事情。浏览器之间的不一致性本身就是一场噩梦。我最终使用了这个很棒的小图书馆。 https://github.com/rndme/download
它的优点是它的灵活性,不仅url,而且客户端数据你想要下载。
文本字符串 文本dataURL 文本的团 文本数组 html字符串 html的团 ajax回调 二进制文件
其他回答
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
使用锚标签和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");
}
我知道我迟到了,但我想分享我的解决方案,这是上面Imagine Breaker解决方案的变化。我试着用他的方法,因为他的方法对我来说是最简单易行的。但就像其他人说的那样,它不适合某些浏览器,所以我使用jquery对它进行了一些修改。
希望这能帮助到那里的人。
function download(url) {
var link = document.createElement("a");
$(link).click(function(e) {
e.preventDefault();
window.location.href = url;
});
$(link).click();
}
我建议使用下载属性而不是jQuery:
<a href="your_link" download> file_name </a>
这将下载您的文件,而不需要打开它。
仅仅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>