您的位置:首页 > 其它

利用Servlet发送pdf文件到浏览器

2017-06-19 23:35 267 查看
public class Test extends HttpServlet{

private static final long serialVersionUID = 1L;

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
sendPDF(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
sendPDF(req, resp);
}

public void sendPDF(HttpServletRequest request,HttpServletResponse response) throws IOException {

//设置发送到客户端响应的内容类型,浏览器会根据不同的MIME,调用不同的模块处理
response.setContentType("application/pdf");
ServletOutputStream out = response.getOutputStream();
File pdf = null;
BufferedInputStream buf = null;

try {
//调用初始化在web.xml中存放的参量
//String path = getInitParameter("path");
String path = "D:\\aa.pdf";
pdf = new File(path);
response.setContentLength((int) pdf.length());	//设置文件长度
FileInputStream input = new FileInputStream(pdf);
//带缓冲区的输入流
//ileInputStream是字节流,BufferedInputStream是字节缓冲流,使用BufferedInputStream读资源比FileInputStream读取资源的效率高
buf = new BufferedInputStream(input);
int readBytes = 0;

while ((readBytes = buf.read()) != -1) {
out.write(readBytes);
}
} catch (Exception e) {
System.out.println("文件没有找到");
}finally {
if (out != null) {
out.close();
}
if (buf != null) {
buf.close();
}
}
}
}
WEB.xml配置Servlet
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>com.Test</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/TestServlet</url-pattern>
</servlet-mapping>



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  servlet