JAVA下載功能的實現和解析

來源:互聯網
上載者:User

標籤:

下載的首要任務就是就是擷取到

  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下載功能的實現和解析

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.