使用response中的OutputStream进行文件下载

这里写图片描述

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//使用response获得字节输出流
ServletOutputStream out=response.getOutputStream();

    //获得服务器上面的图片
    String realpath=this.getServletContext().getRealPath("456.png");
    InputStream in=new FileInputStream(realpath);
    int len=0;
    byte[] buffer=new byte[1024];
    while((len=in.read(buffer))>0){
        out.write(buffer,0,len);
    }
    in.close();
    out.close();    
}

注意代码中采用了循环,是为了防止文件过大,而采用循环的方式逐步输出

猜你喜欢

转载自blog.csdn.net/czjlghndcy/article/details/80232110