博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JAVA下载功能的实现和解析
阅读量:4937 次
发布时间:2019-06-11

本文共 4674 字,大约阅读时间需要 15 分钟。

下载的首要任务就是就是获取到

  HttpServletRequest  request = this.getRequest();

//获取servlet的请求参数

     HttpServletResponse response= this.getResponse();

//获取到servlet的返回参数

    response.setHeader("Accept-Ranges", "bytes");

//表明服务器支持指定范围请求及byte类型的分段请求

    response.setHeader("Content-disposition", "attachment; filename=" + encodeFileName(文件名));

//对应的解释是:http://www.cnblogs.com/brucejia/archive/2012/12/24/2831060.html

    String contentType = servletContext.getMimeType(文件名);

//获取到文件名的类型

    response.setContentType(contentType != null ? contentType : "application/octet-stream");
//根据不同的数据类型来返回不同的数据
    if ((request.getHeader("Range")!= null) && (!"".equals(request.getHeader("Range").trim()))

//判断请求头是否为空

      normalRender();
    else
      rangeRender();
  }
//对文件名进行编码
  private String encodeFileName(String fileName) {
    try {
      return new String(fileName.getBytes("GBK"), "ISO8859-1"); } catch (UnsupportedEncodingException e) {
    }
    return fileName;
  }
  private void normalRender()
  {
    this.response.setHeader("Content-Length", String.valueOf(this.file.length()));

//设置相应体的长度后写入写出。

    InputStream inputStream = null;
    OutputStream outputStream = null;
    try {
      inputStream = new BufferedInputStream(new FileInputStream(this.file));
      outputStream = this.response.getOutputStream();
      byte[] buffer = new byte[1024];
      for (int len = -1; (len = inputStream.read(buffer)) != -1; ) {
        outputStream.write(buffer, 0, len);
      }
      outputStream.flush();
    }
    catch (IOException e) {
      if (getDevMode()) throw new RenderException(e);
      if (inputStream != null) try {
          inputStream.close(); } catch (IOException localIOException1) {
        } if (outputStream != null) try {
          outputStream.close();
        }
        catch (IOException localIOException2)
        {
        }
    }
    catch (Exception e)
    {
      throw new RenderException(e);
    }
    finally {
      if (inputStream != null) try {
          inputStream.close(); } catch (IOException localIOException3) {
        } if (outputStream != null) try {
          outputStream.close(); } catch (IOException localIOException4) {
        }
    }
  }
  private void rangeRender() {
    Long[] range = new Long[2];
    processRange(range);
    String contentLength = String.valueOf(range[1].longValue() - range[0].longValue() + 1L);
    response.setHeader("Content-Length", contentLength);
    response.setStatus(206);
    StringBuilder contentRange = new StringBuilder("bytes ").append(String.valueOf(range[0])).append("-").append(String.valueOf(range[1])).append("/").append(String.valueOf(this.file.length()));
    this.response.setHeader("Content-Range", contentRange.toString());
    InputStream inputStream = null;
    OutputStream outputStream = null;
    try {
      long start = range[0].longValue();
      long end = range[1].longValue();
      inputStream = new BufferedInputStream(new FileInputStream(this.file));
      if (inputStream.skip(start) != start)
        throw new RuntimeException("File skip error");
      outputStream = this.response.getOutputStream();
      byte[] buffer = new byte[1024];
      long position = start;
      int len;
      while ((position <= end) && ((len = inputStream.read(buffer)) != -1))
      {
        int len;
        if (position + len <= end) {
          outputStream.write(buffer, 0, len);
          position += len;
        }
        else {
          for (int i = 0; (i < len) && (position <= end); i++) {
            outputStream.write(buffer[i]);
            position += 1L;
          }
        }
      }
      outputStream.flush();
    }
    catch (IOException e) {
      if (getDevMode()) throw new RenderException(e);
      if (inputStream != null) try {
          inputStream.close(); } catch (IOException localIOException1) {
        } if (outputStream != null) try {
          outputStream.close();
        }
        catch (IOException localIOException2)
        {
        }
    }
    catch (Exception e)
    {
      throw new RenderException(e);
    }
    finally {
      if (inputStream != null) try {
          inputStream.close(); } catch (IOException localIOException3) {
        } if (outputStream != null) try {
          outputStream.close();
        }
        catch (IOException localIOException4)
        {
        }
    }
  }
  private void processRange(Long[] range)
  {
    String rangeStr = this.request.getHeader("Range");
    int index = rangeStr.indexOf(',');
    if (index != -1)
      rangeStr = rangeStr.substring(0, index);
    rangeStr = rangeStr.replace("bytes=", "");
    String[] arr = rangeStr.split("-", 2);
    if (arr.length < 2) {
      throw new RuntimeException("Range error");
    }
    long fileLength = this.file.length();
    for (int i = 0; i < range.length; i++) {
      if (StrKit.notBlank(arr[i])) {
        range[i] = Long.valueOf(Long.parseLong(arr[i].trim()));
        if (range[i].longValue() >= fileLength) {
          range[i] = Long.valueOf(fileLength - 1L);
        }
      }
    }
    if ((range[0] != null) && (range[1] == null)) {
      range[1] = Long.valueOf(fileLength - 1L);
    }
    else if ((range[0] == null) && (range[1] != null)) {
      range[0] = Long.valueOf(fileLength - range[1].longValue());
      range[1] = Long.valueOf(fileLength - 1L);
    }
    if ((range[0] == null) || (range[1] == null) || (range[0].longValue() > range[1].longValue()))
      throw new RuntimeException("Range error");
  }
}

转载于:https://www.cnblogs.com/jonesWang/p/4586334.html

你可能感兴趣的文章
操作引入xml文件的书包(定位到指定节点)
查看>>
操作系统学习笔记系列(一)- 导论
查看>>
已计划将多个默认网关用于提供单一网络
查看>>
CSS实例:图片导航块
查看>>
python进阶七_文件操作(三)
查看>>
window的对象有哪些(笔记)
查看>>
成绩查询方法指引Pmp
查看>>
Boolean Expressions
查看>>
They Are Everywhere
查看>>
数据结构--汉诺塔递归Java实现
查看>>
day14 多态与抽象
查看>>
Eclipse CDT 出现 launch failed Binary not found
查看>>
apache jmeter
查看>>
Linux 基本命令
查看>>
RedHat7.0 网络源的配置
查看>>
(Mark)JS中关于闭包
查看>>
流程结构图
查看>>
ios端web app在键盘升起后缩小view防止界面仍可上下滑动
查看>>
从service弹出系统级自定义提示框,可在任意页面弹出
查看>>
Bootstrap简单介绍
查看>>