通过servlet下载图片

下载页面:

<!DOCTYPE html>
     <html>
         <head>
            <meta charset = "utf-8">
            <title>下载页面</title>
         </head>
         <body>
              <a href ="Download">下载图片</a>
         </body>
     </html>

java servlet code :

@WebServlet("/Download")
public class DownloadServlet extends HttpServlet{
  @Override
  protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IoException{
    //获得绝对路径
    String path = getServletContext().getRealPath("/");

    //创建下载文件的file对象
    File file = new File(path + "/img/img.png");
    
    //读文件
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

    //响应格式
    resp.setHeader("content-disposition","attachment;filename=" + (new String(file.getName().getBytes(),"iso-8895-1")));

    //把文件写到响应输出流
    BufferedOutputStream bos = new BufferedOutputStream(resp.getOutputStream());
     byte[] buff = new byte[1000];
    int length;
    while((length = bis.read(buff)) !=1){
      bos.writer(buff,0,length);
      bos.flush();
    }
    bis.close();
    bos.close();
  }
  @Override
  protected void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
    doGet(req,resp);
  }
}

 

代码中有些类可能是因为包没有导入,会出现一些错误............so,请自行导入............

 

可能会出现单词错误,毕竟我是手写进去的......................

 

 

posted @ 2017-09-21 10:09  V尊者  阅读(537)  评论(0)    收藏  举报