servlet的方式下载二进制流PDF文件的方法

public void getSop(HttpServletRequest request, HttpServletResponse response,String sopId)
			throws ServletException, IOException {

		InputStream is = null;
		DataInputStream dis = null;
		
		E_SOP_Detail eDetail = (E_SOP_Detail) session.get(E_SOP_Detail.class,
				sopId);
		if (eDetail == null) {
			request.getRequestDispatcher("/findSOPID.jsp").forward(request,
					response);
//			response.sendRedirect("/findSOPID.jsp");
		} else {
			Blob blob = eDetail.getSop_doc();
			response.setContentType("application/octet-stream");//application/pdf
			ServletOutputStream sos = response.getOutputStream();
			try {
				// 讀取blob內容寫入至檔中
				is = blob.getBinaryStream();
				dis = new DataInputStream(is);
				int len;
				while ((len = dis.read()) != -1) {
					sos.write(len);
				}
				sos.flush();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					is.close();
					dis.close();
					sos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}


你可能感兴趣的:(servlet的方式下载二进制流PDF文件的方法)