标签:ted end eal ons 服务器 pos 浏览器 字节 响应
public class HelloServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置浏览器响应的mime类型 response.setContentType("application/msword"); //从服务器中获取要下载的文件的路径 String realPath = getServletContext().getRealPath("/error/myword.docx"); File file = new File(realPath); try { //获取该文件的输入流 FileInputStream inputStream = new FileInputStream(file); //通过response获取ServletOutputStream对象(out) ServletOutputStream outputStream = response.getOutputStream(); //通过字节流的方式将文件写会浏览器 int b = 0; byte[] buffer = new byte[1024]; while (b != -1){ b = inputStream.read(buffer); //写到输出流(out)中 outputStream.write(buffer,0,b); } inputStream.close(); outputStream.close(); outputStream.flush(); } catch (IOException e) { e.printStackTrace(); } } }
标签:ted end eal ons 服务器 pos 浏览器 字节 响应
原文地址:http://www.cnblogs.com/realshijing/p/7811128.html