码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA下载功能的实现和解析

时间:2015-06-18 19:10:06      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

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

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

JAVA下载功能的实现和解析

标签:

原文地址:http://www.cnblogs.com/jonesWang/p/4586334.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!