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 o开发者_开发知识库pening it in the same or different window in the browser? I've seen some examples of how to do this in PHP, but not Java.
Not sure if compiled vs. interpreted languages could have anything to do with why I can't find a Java solution. (Random thought)
You need to set the Content-Type
and Content-Disposition
headers. Assuming response
is an HttpServletResponse
object,
String filename = "foo.pdf";
response.setHeader("Content-Type", "application/pdf");
response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
More info: The BalusC Code: 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.
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);
You want to set a Content-disposition header
精彩评论