我正在尝试显示另存为对话框来保存 PDF 文件。这应该在单击 JSP 中的链接时发生。单击此链接时,我调用了一个 struts 操作,它准备 PDF 并转发到另一个我想用于下载框的 JSP 'download.jsp'。
我尝试使用“document.execCommand”,但似乎这只适用于 .txt 和 .html 文件。
然后我尝试通过设置响应头和内容类型来做到这一点。以下是我的 download.jsp 中的代码。但这会将垃圾字符写入我的浏览器。
请让我知道这个问题的解决方案。
<%@ page language="java" import="javax.servlet.ServletOutputStream,java.io.BufferedOutputStream,java.io.DataInputStr eam,java.io.File,java.io.FileInputStream"%><%
response.setHeader("Content-Disposition","attachment;filename=\"" + "mandateOut.pdf" + "\"");
response.setContentType( "application/pdf" );
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "max-age=0");
File file = new File(<fully qualified file name>);
response.setContentLength( (int)file.length() );
// get the OutputStream and buffer our bytes to it
ServletOutputStream outStream = response.getOutputStream();
byte[] buf = new byte[1024];
DataInputStream in = new DataInputStream(new FileInputStream(file));
int len;
while ((in != null) && ((len = in.read(buf)) != -1))
{
outStream.write(buf,0,len);
}
// keep the page from freaking out over our use of it's outputstream
in.close();
outStream.flush();
outStream.close();
%>