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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zgsxhdzxl/article/details/73478218
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>


 

猜你喜欢

转载自blog.csdn.net/zgsxhdzxl/article/details/73478218
今日推荐