athrunwang

          紀元
          數據加載中……
          Java 下載支持斷點續傳

          [代碼] [Java]代碼,服務器端實現

          File file = new File(location);                        
                                  if (file.exists()) {                                        
                                      long p = 0;
                                      long fileLength;
                                      fileLength = file.length();
                                      
                                      // get file content
                                      InputStream ins = new FileInputStream(file);
                                      bis = new BufferedInputStream(ins);                            
                                      
                                      // tell the client to allow accept-ranges
                                      response.reset();
                                      response.setHeader("Accept-Ranges", "bytes");
                                      
                                      // client requests a file block download start byte
                                      if (request.getHeader("Range") != null) {                                
                                          response.setStatus(javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT);
                                          p = Long.parseLong(request.getHeader("Range")
                                                  .replaceAll("bytes=", "")
                                                  .replaceAll("-", "")
                                                  );                                
                                      }
                                      // support multi-threaded download
                                      // respone format:
                                      // Content-Length:[file size] - [client request start bytes from file block]
                                      response.setHeader("Content-Length", new Long(fileLength - p).toString());
                                      
                                      if (p != 0) {
                                          // 斷點開始
                                          // 響應的格式是:
                                          // Content-Range: bytes [文件塊的開始字節]-[文件的總大小 - 1]/[文件的總大小]
                                          String contentRange = new StringBuffer("bytes ")
                                                  .append(new Long(p).toString())
                                                  .append("-")
                                                  .append(new Long(fileLength - 1).toString())
                                                  .append("/")
                                                  .append(new Long(fileLength).toString())
                                                  .toString();
                                          response.setHeader("Content-Range", contentRange);
                                          // pointer move to seek
                                          bis.skip(p);
                                      }
                                      
                                      String fileName = file.getName();
                                      response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
                                                   
                                      while ((size = bis.read(buf)) != -1) {
                                          response.getOutputStream().write(buf,0,size);
                                          response.getOutputStream().flush();                                
                                      }
                                      bis.close();

          [代碼] 客戶端下載測試

          public class TestDownload {

              /**
               * @param args
               */
              public static void main(String[] args) {
                  // TODO Auto-generated method stub
                  HttpURLConnection httpURLConnection = null;
                  URL url = null;
                  BufferedInputStream bis = null;
                  byte[] buf = new byte[10240];
                  int size = 0;
                  String fileName = "aaa.zip";
                  String filePath = "C:\\Users\\Desktop";
                  String remoteUrl = "http://127.0.0.1:8080/down.zip";

                  // 檢查本地文件
                  RandomAccessFile rndFile = null;
                  File file = new File(filePath + "\\" + fileName);
                  long remoteFileSize = getRemoteFileSzie(remoteUrl);
                  long nPos = 0;
                 
                  if (file.exists()) {                       
                      long localFileSzie = file.length();
                      if (localFileSzie < remoteFileSize) {                   
                          System.out.println("文件續傳...");
                          nPos = localFileSzie;
                      } else {
                          System.out.println("文件存在,重新下載...");
                          file.delete();
                          try {
                              file.createNewFile();
                          } catch (Exception e) {
                              // TODO: handle exception
                              e.printStackTrace();
                          }   
                      }
                     
                  } else {
                      // 建立文件
                      try {
                          file.createNewFile();
                      } catch (Exception e) {
                          // TODO: handle exception
                          e.printStackTrace();
                      }           
                  }
                 
                  // 下載文件
                  try {
                      url = new URL(remoteUrl);       
                      httpURLConnection = (HttpURLConnection)url.openConnection();
                      // 設置User-Agent
                      httpURLConnection.setRequestProperty("User-Agent", "Net");
                      // 設置續傳開始
                      httpURLConnection.setRequestProperty("Range", "bytes=" + nPos + "-");
                      // 獲取輸入流
                      bis = new BufferedInputStream(httpURLConnection.getInputStream());           
                      rndFile = new RandomAccessFile(filePath + "\\" + fileName, "rw");
                      rndFile.seek(nPos);
                      int i = 0;
                      while ((size = bis.read(buf)) != -1) {
                          //if (i > 500) break;               
                          rndFile.write(buf, 0, size);
                         
                          i++;
                      }
                      System.out.println("i=" + i);
                      httpURLConnection.disconnect();
                  } catch (Exception e) {
                      // TODO: handle exception
                      e.printStackTrace();
                  }
              }

              public static long getRemoteFileSzie(String url) {
                  long size = 0;
                  try {
                      HttpURLConnection httpUrl = (HttpURLConnection)(new URL(url)).openConnection();
                      size = httpUrl.getContentLength();
                      httpUrl.disconnect();           
                  } catch (Exception e) {
                      // TODO: handle exception
                      e.printStackTrace();
                  }
                  return size;
              }
          }

          posted on 2012-01-02 17:31 AthrunWang 閱讀(460) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 新巴尔虎左旗| 平湖市| 康马县| 当雄县| 会同县| 集安市| 昌邑市| 公安县| 常熟市| 静乐县| 体育| 双柏县| 东乌珠穆沁旗| 张家港市| 鄂伦春自治旗| 胶南市| 缙云县| 石嘴山市| 莱州市| 韶关市| 新河县| 万载县| 通道| 任丘市| 墨江| 保定市| 邮箱| 大庆市| 浏阳市| 剑阁县| 松潘县| 美姑县| 临海市| 漳平市| 邯郸市| 民和| 巴青县| 宁海县| 陆河县| 遂昌县| 名山县|