我有一些大尺寸的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/
通常会发生这种情况,因为一些浏览器设置或插件会直接在同一个窗口中打开PDF,就像一个简单的网页。
以下内容可能会对你有所帮助。几年前我用PHP做过。但目前我还没有在这个平台上工作。
<?php
if (isset($_GET['file'])) {
$file = $_GET['file'];
if (file_exists($file) && is_readable($file) && preg_match('/\.pdf$/',$file)) {
header('Content-type: application/pdf');
header("Content-Disposition: attachment; filename=\"$file\"");
readfile($file);
}
}
else {
header("HTTP/1.0 404 Not Found");
echo "<h1>Error 404: File Not Found: <br /><em>$file</em></h1>";
}
?>
将上述文件保存为download.php。
将这个小片段保存为服务器某处的PHP文件,您可以使用它在浏览器中进行文件下载,而不是直接显示。如果要提供PDF以外的文件,请删除或编辑第5行。
你可以这样使用它:
将以下链接添加到HTML文件中。
<a href="download.php?file=my_pdf_file.pdf">Download the cool PDF.</a>
参考来源:这个博客
我只是有一个非常类似的问题,我需要在一个ZIP文件中创建下载链接。
我首先尝试创建一个临时文件,然后提供一个到临时文件的链接,但我发现一些浏览器只会显示内容(一个CSV Excel文件)而不提供下载。最终我通过使用servlet找到了解决方案。它可以在Tomcat和GlassFish上运行,我还在Internet Explorer 10和Chrome上试用了它。
servlet将ZIP文件的完整路径名和应该下载的ZIP文件中的文件名作为输入。
在我的JSP文件中,我有一个表,显示zip中的所有文件,其中的链接说:onclick='download?邮政= < % = zip % > csv = < % = % > csv '
servlet代码在download.java中:
package myServlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.zip.*;
import java.util.*;
// Extend HttpServlet class
public class download extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter(); // now we can write to the client
String filename = request.getParameter("csv");
String zipfile = request.getParameter("zip");
String aLine = "";
response.setContentType("application/x-download");
response.setHeader( "Content-Disposition", "attachment; filename=" + filename); // Force 'save-as'
ZipFile zip = new ZipFile(zipfile);
for (Enumeration e = zip.entries(); e.hasMoreElements();) {
ZipEntry entry = (ZipEntry) e.nextElement();
if(entry.toString().equals(filename)) {
InputStream is = zip.getInputStream(entry);
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 65536);
while ((aLine = br.readLine()) != null) {
out.println(aLine);
}
is.close();
break;
}
}
}
}
要在Tomcat上编译,你需要类路径包含Tomcat \lib\servlet-api.jar或GlassFish上的:GlassFish \lib\j2ee.jar
但任何一种都能同时发挥作用。您还需要在web.xml中设置servlet。