File download using OutputStream in response

write picture description here

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();    
}

Note that the loop is used in the code to prevent the file from being too large, and the loop is used to output step by step

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325992004&siteId=291194637
Recommended