[英]How to link to pdf as file with Java
Is there a way in Java/.jsp to set the content type, etc... so that a link to a pdf prompts the user to save it rather than opening it in the same or different window in the browser? Java / .jsp中是否可以设置内容类型等方式,以便指向pdf的链接提示用户保存它,而不是在浏览器的相同或不同窗口中打开它? I've seen some examples of how to do this in PHP, but not Java.
我已经看到了一些用PHP而不是Java进行操作的示例。
Not sure if compiled vs. interpreted languages could have anything to do with why I can't find a Java solution. 不确定编译语言与解释语言是否与为什么我找不到Java解决方案有关。 (Random thought)
(随机思想)
You need to set the Content-Type
and Content-Disposition
headers. 您需要设置
Content-Type
和Content-Disposition
标头。 Assuming response
is an HttpServletResponse
object, 假设
response
是一个HttpServletResponse
对象,
String filename = "foo.pdf";
response.setHeader("Content-Type", "application/pdf");
response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
More info: The BalusC Code: FileServlet . 更多信息: BalusC代码:FileServlet 。
If the PDF is not autogenerated or read from an external location by a servlet, but just present in the public webcontent, then it suffices to map a Filter
on an URL pattern of *.pdf
(or whatever more specific/generic) which does the following job in the doFilter()
method. 如果PDF不是由servlet自动生成或从外部读取,而只是出现在公共Web内容中,则足以将
Filter
映射到*.pdf
(或更具体的/更通用的)URL模式上, doFilter()
方法中的后续作业。
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String filename = req.getRequestURI().substring(req.getRequestURI().lastIndexOf('/') + 1);
res.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
chain.doFilter(request, response);
您想要设置一个Content-disposition标头
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.