利用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>
相关文章推荐
- 利用FlashPaper在web页面中显示PDF文件(兼容各浏览器)
- 【java】servlet输出pdf文件到浏览器 教程
- 利用Ajax向Servlet发送请求下载统计后的Excel文件,利用jquery.blockUI.js给予用户等待提示
- 利用FlashPaper在web页面中显示PDF文件(兼容各浏览器)
- 利用itextsharp生成pdf并生成zip文件及其邮件发送
- Dynemic Web Project中使用servlet的 doGet()方法接收来自浏览器客户端发送的add学生信息形成json字符串输出到浏览器并保存到本地磁盘文件
- 利用pdfJS实现以读取文件流方式在线展示pdf文件
- 利用HttpClient模拟form表单将文件上传到Servlet
- ASP.NET MVC:通过 FileResult 向 浏览器 发送文件
- MVC学习四:通过FileResult向浏览器发送文件
- 利用adobe reader批量在线打印pdf文件
- 利用pdfbox读取pdf文件内容和图片
- 利用java的iText操作PDF文件
- 利用itextsharp.dll 导出pdf格式文件
- 利用Python的Django框架生成PDF文件的教程
- web项目中servlet利用servletContext对象读取资源文件
- 利用PDFLIB开发库生成PDF文件
- 利用PDFLIB开发库生成PDF文件
- 利用静态数组和内存流在MQ中发送接收文件
- 浏览器显示pdf文件