servlet下载文件

@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //路径为目标文件,可以是文件、图片、压缩包等
        File file = new File("E://commons-beanutils-1.9.3-bin.zip");
        //创建一个文件输入流
        FileInputStream inputStream = new FileInputStream(file);
        //注意:标记是下载文件必须要这句
        resp.setHeader("content-disposition", "attachment;filename="+file.getName());
        //文件写出
        ServletOutputStream outputStream = resp.getOutputStream();
        byte[] bt = new byte[1024];
        int len;
        while((len = inputStream.read(bt))!= -1) {
            outputStream.write(bt,0,len);
        }
        inputStream.close();
    }

 

posted @ 2017-10-30 20:12  呆木头2号  阅读(162)  评论(0编辑  收藏  举报