我在这里指定了一个非常类似的需求。
我需要有用户的浏览器手动启动下载时$('a#someID').click();
但是我不能用窗户。Href方法,因为它将当前页面内容替换为您试图下载的文件。
相反,我想在新窗口/标签中打开下载。这怎么可能呢?
我在这里指定了一个非常类似的需求。
我需要有用户的浏览器手动启动下载时$('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');
其他回答
使用锚标签和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");
}
你必须从服务器和客户端(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()
}
这样就行了。
如果您已经在使用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');
注意:并非所有浏览器都支持。
我正在寻找一种方法,使用jquery下载文件,而不必从一开始就在href属性中设置文件url。
jQuery (< / >, { id:“downloadFile”, href:“http://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png”, 风格:“显示:隐藏。” 下载:“ }) .appendTo(身体的); $ (" # downloadFile ") [0] .click (); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本>
也可以使用fs-浏览器包。 它有很好的和简单的下载方法为客户端。 它是这样的:
import {downloadFile} from 'fs-browsers'; downloadFile (url-to-the-file);