码迷,mamicode.com
首页 > 其他好文 > 详细

文件下载

时间:2017-11-09 21:01:08      阅读:147      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!