zoukankan      html  css  js  c++  java
  • Http方式下载Servlet实现

    Http方式下载,Servlet实现

    与普通的Servlet处理请求类似,浏览器端输入URL,该URLtomcat分配给相应的Servlet进行处理,以下为示例代码:

     1 public void service(HttpServletRequest req, HttpServletResponse res) {
    2
    3 File file = new File(fileName);
    4 if(file.exists()) {
    5 FileInputStream in = new FileInputStream(file);
    6 try {
    7 res.setContentType("application/zip");
    8 res.setContentLength( (int)file.length() );
    9 res.setHeader("Content-Disposition", "attachment; filename=\""+fileName+"\"");
    10 ServletOutputStream out = res.getOutputStream();
    11 int read = 0;
    12 byte buf[] = new byte[4096];
    13 while ((read = in.read(buf, 0, 4096)) != -1)
    14 {
    15 out.write(buf, 0, read);
    16 }
    17 if (out != null)
    18 {
    19 out.close();
    20 }
    21 in.close();
    22 file.delete();
    23 } catch (IOException e) {
    24 System.out.println(fileName+" 文件下载出错");
    25 e.printStackTrace();
    26 }
    27 } else {
    28 System.out.println(fileName+" 文件不存在");
    29 }
    30 }



     

  • 相关阅读:
    HDU 1495 广度优先搜索
    oj 1792:迷宫 广搜和深搜
    oj 1756:八皇后 搜索
    OJ1700 八皇后问题 基本搜索算法
    PAT A1020
    PAT A1103
    PAT A1046 Shortest Distance
    PAT A1059
    PAT B1013
    二分查找
  • 原文地址:https://www.cnblogs.com/un4sure/p/2194440.html
Copyright © 2011-2022 走看看