我有一些大尺寸的PDF目录在我的网站上,我需要链接这些下载。当我在谷歌上搜索时,我发现下面有这样一件事。它应该打开“另存为…”弹出链接点击…

 <head>
    <meta name="content-disposition" content="inline; filename=filename.pdf">
    ...

但它不工作:/当我链接到一个文件如下,它只是链接到文件,并试图打开文件。

    <a href="filename.pdf" title="Filie Name">File name</a>

更新(根据以下答案):

据我所知,没有100%可靠的跨浏览器解决方案。也许最好的方法是使用下面列出的web服务之一,并提供下载链接…

http://box.net/ http://droplr.com/ http://getcloudapp.com/


当前回答

只要把下面的代码放在你的。htaccess文件中:

AddType application/octet-stream .csv
AddType application/octet-stream .xls
AddType application/octet-stream .doc
AddType application/octet-stream .avi
AddType application/octet-stream .mpg
AddType application/octet-stream .mov
AddType application/octet-stream .pdf

或者你也可以通过JavaScript来实现

element.setAttribute( 'download', whatever_string_you_want);

其他回答

如果你需要强制下载页面上的单个链接,一个非常简单的方法就是使用href-link中的HTML5 download-属性。

参见:http://davidwalsh.name/download-attribute

有了这个,你可以重命名用户将下载的文件,同时它强制下载。

这是否是一种好的做法一直存在争议,但在我的情况下,我有一个PDF文件的嵌入式查看器,查看器不提供下载链接,所以我必须单独提供一个。在这里,我希望确保用户不会在web浏览器中打开PDF文件,否则会令人困惑。

这将不需要打开另存为对话框,但将下载链接直接到预设的下载目的地。当然,如果你是为别人做一个网站,需要他们手动写属性到他们的链接可能是一个坏主意,但如果有办法让属性到链接,这可能是一个简单的解决方案。

我刚刚用了这个,但我不知道它是否适用于所有浏览器。

它适用于Firefox:

<a href="myfile.pdf" download>Click to Download</a>

添加响应头Content-Disposition:附件;后面跟着文件名。删除Meta Content-Disposition;Inline;哪个会在同一个窗口中打开文档

在java中,它被设置为

response.setHeader("Content-Disposition", "attachment;filename=test.jpg");

我为Firefox找到了一个非常简单的解决方案(只适用于相对而不是直接href): add type="application/octet-stream":

<a href="./file.pdf" id='example' type="application/octet-stream">Example</a>

元标签并不是实现这一结果的可靠方法。一般来说,你甚至不应该这样做——应该由用户/用户代理来决定如何处理你提供的内容。如果用户愿意,总是可以强制浏览器下载文件。

如果您仍然希望强制浏览器下载文件,请直接修改HTTP报头。下面是一个PHP代码示例:

$path = "path/to/file.pdf";
$filename = "file.pdf";
header('Content-Transfer-Encoding: binary');  // For Gecko browsers mainly
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($path)) . ' GMT');
header('Accept-Ranges: bytes');  // Allow support for download resume
header('Content-Length: ' . filesize($path));  // File size
header('Content-Encoding: none');
header('Content-Type: application/pdf');  // Change the mime type if the file is not PDF
header('Content-Disposition: attachment; filename=' . $filename);  // Make the browser display the Save As dialog
readfile($path);  // This is necessary in order to get it to actually download the file, otherwise it will be 0Kb

请注意,这只是对HTTP协议的扩展;有些浏览器可能会忽略它。