javascript 使用 servlet 在浏览器中显示 PDF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14202892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Display PDF in browser with a servlet
提问by user856354
I want to display a PDF file in browser. I have the path to the pdf in JS and I am making a call to grab the PDF as a servlet from java. Here's what I have so far:
我想在浏览器中显示一个 PDF 文件。我在 JS 中有 pdf 的路径,我正在调用以从 java 获取 PDF 作为 servlet。这是我到目前为止所拥有的:
JavaScript:
JavaScript:
RequestManager.getJSON(Config.server + "getPDF.json?pdfPath=" + this.pathToPdfFile, (function(data){
$("#" + this.divId).append('<object id="' + this.pdfObjectId + '" data="' + data + '" type="application/pdf" width="600" height="800"></object>');
ResizeManager.addResizeHandler(this.pdfObjectId, this.divId, -10, -10);
}).bind(this));
Java:
爪哇:
@RequestMapping("/getPDF")
public void pdfPathToServlet(Model model, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String pdfPath = request.getParameter("pdfPath");
if (pdfPath == null || pdfPath.equals(""))
throw new ServletException("Invalid or non-existent file parameter in UrlServlet servlet.");
if (pdfPath.indexOf(".pdf") == -1)
pdfPath += ".pdf";
File pdf = new File(pdfPath);
String pdfName = pdfPath.substring(pdfPath.lastIndexOf("/") + 1, pdfPath.length());
logger.debug(pdfName);
ServletOutputStream stream = null;
BufferedInputStream buf = null;
try
{
stream = response.getOutputStream();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "inline; filename='" + pdfName + "'");
FileInputStream input = new FileInputStream(pdf);
response.setContentLength((int) pdf.length());
buf = new BufferedInputStream(input);
int readBytes = 0;
while ((readBytes = buf.read()) != -1)
stream.write(readBytes);
}
catch (IOException ioe)
{
throw new ServletException(ioe.getMessage());
}
finally
{
if (stream != null)
stream.close();
if (buf != null)
buf.close();
}
}
My problem is that this is showing the binary outputin my browser as text.
我的问题是这将我的浏览器中的二进制输出显示为文本。
I'm not sure what I am doing incorrectly. I have tried changing the header to be attachment instead of inline, but that showed the same thing. I believe I want inline though, as I wish to show it in browser and not download it.
我不确定我做错了什么。我曾尝试将标题更改为附件而不是内联,但这显示了相同的内容。我相信我想要内联,因为我希望在浏览器中显示它而不是下载它。
回答by BalusC
Your JavaScript part makes no sense. You're obtaining a PDF file as ajax response and then attempting to set it as data
attribute of the <object>
element. The data
attribute must point to a real URL, not to the file content. Fix your JS accordingly:
你的 JavaScript 部分没有意义。您正在获取 PDF 文件作为 ajax 响应,然后尝试将其设置为元素的data
属性<object>
。该data
属性必须指向真实的 URL,而不是文件内容。相应地修复您的 JS:
$("#" + this.divId).append('<object id="' + this.pdfObjectId + '" data="' + Config.server + "getPDF.json?pdfPath=" + this.pathToPdfFile + '" type="application/pdf" width="600" height="800"></object>');
The webbrowser will take care about sending the appropriate HTTP request on the given URL and initializing/rendering the <object>
element using the Adobe Acrobat Reader plugin — if any available, I'd rather enclose a <a href="pdfURL">PDF</a>
inside the <object>
so that there's at least a graceful degradation to a download link.
网络浏览器将负责在给定的 URL 上发送适当的 HTTP 请求,并<object>
使用 Adobe Acrobat Reader 插件初始化/渲染元素——如果有的话,我宁愿在<a href="pdfURL">PDF</a>
里面附上一个,<object>
这样至少可以优雅地降级为下载链接。
Unrelatedto the concrete question, that Java code is not part of a servlet at all, but a Spring MVC action. I recommend to get your terms straight and read in our Servlets wiki pageto learn what they really are.
与具体问题无关,Java 代码根本不是 servlet 的一部分,而是 Spring MVC 操作。我建议直接了解您的术语并阅读我们的 Servlets wiki 页面以了解它们的真正含义。
回答by Moritz Petersen
response.setHeader("Content-Disposition", "attachment;filename=" + pdfName);
回答by Diodeus - James MacFarlane
response.setHeader("Content-Disposition", "inline; filename='" + pdfName + "'");
You cannot display a PDF inline. It needs to be alone on its own page (or Iframe).
您无法内联显示 PDF。它需要单独存在于自己的页面(或 Iframe)上。