1 /**
2 * 重新設置http response參數,使之支持斷點續傳.
3 *
4 * @param fileLength
5 * 文件長度.
6 * @throws IOException
7 *
8 */
9 private void resetResponse(long fileLength) throws IOException {
10 long p = 0;
11 long l = fileLength;
12
13 ServletActionContext.getResponse().reset();
14 // 告訴客戶端允許斷點續傳多線程連接下載
15 // 響應的格式是:
16 // Accept-Ranges: bytes
17
18 ServletActionContext.getResponse().setHeader("Accept-Ranges", "bytes");
19 // 如果是第一次下,還沒有斷點續傳,狀態是默認的 200,無需顯式設置
20 // 響應的格式是:
21 // HTTP/1.1 200 OK
22
23 if (ServletActionContext.getRequest().getHeader("Range") != null) // 客戶端請求的下載的文件塊的開始字節
24 {
25
26 ServletActionContext.getResponse().setStatus(
27 javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT);
28 p = Long.parseLong(ServletActionContext.getRequest().getHeader(
29 "Range").replaceAll("bytes=", "").replaceAll("-", ""));
30 }
31
32 //如果設設置了Content-Length,則客戶端會自動進行多線程下載。如果不希望支持多線程,則不要設置這個參數。
33 // 響應的格式是:
34 // Content-Length: [文件的總大小] - [客戶端請求的下載的文件塊的開始字節]
35 // ServletActionContext.getResponse().setHeader("Content-Length",
36 // new Long(file.length() - p).toString());
37
38 if (p != 0) {
39
40 // 不是從最開始下載,
41 // 響應的格式是:
42 // Content-Range: bytes [文件塊的開始字節]-[文件的總大小 - 1]/[文件的總大小]
43 String contentRange = new StringBuffer("bytes ")
44 .append(new Long(p).toString())
45 .append("-")
46 .append(new Long(l - 1).toString())
47 .append("/")
48 .append(new Long(l).toString())
49 .toString();
50 ServletActionContext.getResponse().setHeader("Content-Range",
51 contentRange);
52 LogService.info("Content-Range is : " + contentRange);
53 }
54
55 _fileStream.skip(p);
56
57 }
正如代碼所示,實現斷點續傳和多線程下載的關鍵在于對response的參數進行設置。
posted on 2007-04-03 09:04
OO 閱讀(4320)
評論(2) 編輯 收藏 所屬分類:
java相關的亂七八糟的東西