当用户点击链接时,如何提示下载?
例如,不是:
<a href="uploads/file.doc">Download Here</a>
我可以使用:
<a href="#">Download Here</a>
$('a').click... //Some jquery to download the file
这种方法可以避免 Google 索引我的 HREF 和私有文件。
如果可以的话,是否可以使用 jQuery 来实现?如何实现?或者应该使用 PHP 或其他东西来实现呢?
当用户点击链接时,如何提示下载?
例如,不是:
<a href="uploads/file.doc">Download Here</a>
我可以使用:
<a href="#">Download Here</a>
$('a').click... //Some jquery to download the file
这种方法可以避免 Google 索引我的 HREF 和私有文件。
如果可以的话,是否可以使用 jQuery 来实现?如何实现?或者应该使用 PHP 或其他东西来实现呢?
我可能会建议使用preventDefault
,作为更具优雅降级的解决方案:
$('a').click(function(e) {
e.preventDefault(); //stop the browser from following
window.location.href = 'uploads/file.doc';
});
<a href="no-script.html">Download now!</a>
即使没有JavaScript,使用这种方法至少会让用户得到一些反馈。
robots.txt
是无法帮助的,因为它仍然会存储在浏览器历史记录和中间服务器中。 - Pacerier这是一篇不错的文章,展示了多种隐藏文件使其无法被搜索引擎发现的方法:
JavaScript不是一个不被索引页面的好方法;它不能阻止用户直接链接到您的文件(从而向爬虫机器人揭示它),而且正如Rob所提到的那样,并不能为所有用户生效。
一个简单的修复方法是加上rel="nofollow"
属性,但是同样需要添加robots.txt才能完全生效。
<a href="uploads/file.doc" rel="nofollow">Download Here</a>
var link=document.createElement('a');
document.body.appendChild(link);
link.href=url;
link.click();
使用jQuery函数
var valFileDownloadPath = 'http//:'+'your url';
window.open(valFileDownloadPath , '_blank');
是的,你需要将window.location.href更改为你想要下载的文件的URL。
window.location.href = 'http://www.com/path/to/file';
window.location.href = 'uploads/file.doc';
,您可以显示文件存储的位置。当然,您也可以使用 .htaccess 强制存储文件所需的行为,但这可能不总是方便的......
最好创建一个服务器端 php 文件,并将此内容放入其中:
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$_REQUEST['f']);
readfile('../some_folder/some_subfolder/'.$_REQUEST['f']);
exit;
这段代码可以让你将任何文件作为下载返回,而不显示实际存储的位置。
你可以通过 window.location.href = 'scripts/this_php_file.php?f=downloaded_file';
打开这个 PHP 文件来进行下载。
var link = document.createElement('a');
link.href = "/WWW/test.pdf";
link.download = "file_" + new Date() + ".pdf";
link.click();
link.remove();
我建议您使用mousedown事件,该事件在click事件之前被调用。这样,浏览器可以自然地处理click事件,避免任何代码问题:
(function ($) {
// with this solution, the browser handles the download link naturally (tested in chrome and firefox)
$(document).ready(function () {
var url = '/private/downloads/myfile123.pdf';
$("a").on('mousedown', function () {
$(this).attr("href", url);
});
});
})(jQuery);
var link = document.createElement('a');
document.body.appendChild(link);
link.setAttribute('download', '');
link.href = URL_HERE;
link.click();
link.remove();