我想在瀏覽器中顯示PDF文件。我有通往JS的pdf的路徑,我正在調用從Java獲取PDF作爲servlet。這是我到目前爲止有:使用servlet在瀏覽器中顯示PDF
的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();
}
}
我的問題是,這是表示我的瀏覽器文本二進制輸出。
我不知道我在做什麼不正確。我試圖將標題更改爲附件而不是內聯,但顯示的是相同的內容。我相信我想要內聯,因爲我希望在瀏覽器中顯示它,而不是下載它。
爲什麼當你返回'application/pdf'時,你的網址以'.json'結尾? –
@ Michael-O說實話,我已經把它放在了習慣之外。應用程序編寫的方式是整個應用程序運行的一個URL。它從來沒有真正改變。 .json通常用於防止頁面實際重定向到另一個實際上不包含任何內容的URL。 – user856354
這不是一個servlet。這是一個Spring MVC控制器操作。 – BalusC