use*_*354 3 javascript java pdf servlets
我想在浏览器中显示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));
Run Code Online (Sandbox Code Playgroud)
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();
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,这是在我的浏览器中显示文本的二进制输出.
我不确定我做错了什么.我已经尝试将标题更改为附件而不是内联,但这显示了同样的事情.我相信我想要内联,因为我希望在浏览器中显示它而不是下载它.
你的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>');
Run Code Online (Sandbox Code Playgroud)
webbrowser将负责在给定的URL上发送适当的HTTP请求,并<object>使用Adobe Acrobat Reader插件初始化/呈现元素 - 如果有的话,我宁愿将<a href="pdfURL">PDF</a>内部封装在内部,<object>以便至少有一个优雅的降级下载链接.
与具体问题无关,Java代码根本不是servlet的一部分,而是Spring MVC动作.我建议您直接了解您的术语并阅读我们的Servlets维基页面,了解它们的真实含义.
| 归档时间: |
|
| 查看次数: |
16909 次 |
| 最近记录: |