我想在浏览器中显示 PDF 文件。我在 JS 中有 pdf 的路径,我正在调用从 java 中获取 PDF 作为 servlet。这是我到目前为止所拥有的:
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));
爪哇:
@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();
}
}
我的问题是这将我的浏览器中的二进制输出显示为文本。
我不确定我做错了什么。我尝试将标题更改为附件而不是内联,但这显示了同样的事情。我相信我想要内联,因为我希望在浏览器中显示它而不是下载它。