zoukankan      html  css  js  c++  java
  • Java下载Servlet Demo

     1 request.setCharacterEncoding("utf-8");
     2         String name=request.getParameter("name");
     3         //1、设置响应头
     4         response.setContentType("application/force-download");
     5         //2、读取文件
     6         String path=getServletContext().getRealPath("/file/"+name);
     7         InputStream in=new FileInputStream(path);
     8         //3、对文件名进行编码
     9         name=URLEncoder.encode(name, "utf-8");
    10         //4、设置响应头
    11         response.setHeader("Content-Disposition","attachment;filename="+name);//如果不写attachment,则会在浏览器中打开
    12         response.setContentLength(in.available());
    13         //5、开始copy文件
    14         OutputStream out=response.getOutputStream();
    15         byte[] b=new byte[1024];
    16         int len=-1;
    17         while((len=in.read(b))!=-1)
    18         {
    19             out.write(b, 0, len);
    20         }
    21         out.close();
    22         in.close();
    23         
    24         
    25     }

    写在Servlet中,可以防止盗链,进行过滤等操作

  • 相关阅读:
    Hdu3022 Sum of Digits
    bzoj3864 Hero meet devil
    bzoj2448 挖油
    poj3783 Balls
    bzoj3802 Vocabulary
    Hdu5181 numbers
    Hdu5693 D Game
    图形填充之边标志算法
    图形填充之栅栏填充算法
    图形填充之种子填充算法
  • 原文地址:https://www.cnblogs.com/liuwt365/p/4158225.html
Copyright © 2011-2022 走看看