分享

Java 下载支持断点续传

 闪宁斯达 2011-12-30

[Java]代码,服务器端实现

01 File file = new File(location);                        
02                         if (file.exists()) {                                        
03                             long p = 0;
04                             long fileLength;
05                             fileLength = file.length();
06                               
07                             // get file content
08                             InputStream ins = new FileInputStream(file);
09                             bis = new BufferedInputStream(ins);                            
10                               
11                             // tell the client to allow accept-ranges
12                             response.reset();
13                             response.setHeader("Accept-Ranges", "bytes");
14                               
15                             // client requests a file block download start byte
16                             if (request.getHeader("Range") != null) {                                
17                                 response.setStatus(javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT);
18                                 p = Long.parseLong(request.getHeader("Range")
19                                         .replaceAll("bytes=", "")
20                                         .replaceAll("-", "")
21                                         );                                
22                             }
23                             // support multi-threaded download
24                             // respone format:
25                             // Content-Length:[file size] - [client request start bytes from file block]
26                             response.setHeader("Content-Length", new Long(fileLength - p).toString());
27                               
28                             if (p != 0) {
29                                 // 断点开始
30                                 // 响应的格式是:
31                                 // Content-Range: bytes [文件块的开始字节]-[文件的总大小 - 1]/[文件的总大小]
32                                 String contentRange = new StringBuffer("bytes ")
33                                         .append(new Long(p).toString())
34                                         .append("-")
35                                         .append(new Long(fileLength - 1).toString())
36                                         .append("/")
37                                         .append(new Long(fileLength).toString())
38                                         .toString();
39                                 response.setHeader("Content-Range", contentRange);
40                                 // pointer move to seek
41                                 bis.skip(p);
42                             }
43                               
44                             String fileName = file.getName();
45                             response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
46                                            
47                             while ((size = bis.read(buf)) != -1) {
48                                 response.getOutputStream().write(buf,0,size);
49                                 response.getOutputStream().flush();                                
50                             }
51                             bis.close();

[代码] 客户端下载测试

 
01 public class TestDownload {
02   
03     /**
04      * @param args
05      */
06     public static void main(String[] args) {
07         // TODO Auto-generated method stub
08         HttpURLConnection httpURLConnection = null;
09         URL url = null;
10         BufferedInputStream bis = null;
11         byte[] buf = new byte[10240];
12         int size = 0;
13         String fileName = "aaa.zip";
14         String filePath = "C:\\Users\\Desktop";
15         String remoteUrl = "http://127.0.0.1:8080/down.zip";
16   
17         // 检查本地文件
18         RandomAccessFile rndFile = null;
19         File file = new File(filePath + "\\" + fileName);
20         long remoteFileSize = getRemoteFileSzie(remoteUrl);
21         long nPos = 0;
22          
23         if (file.exists()) {                       
24             long localFileSzie = file.length();
25             if (localFileSzie < remoteFileSize) {                   
26                 System.out.println("文件续传...");
27                 nPos = localFileSzie;
28             } else {
29                 System.out.println("文件存在,重新下载...");
30                 file.delete();
31                 try {
32                     file.createNewFile();
33                 } catch (Exception e) {
34                     // TODO: handle exception
35                     e.printStackTrace();
36                 }   
37             }
38              
39         } else {
40             // 建立文件
41             try {
42                 file.createNewFile();
43             } catch (Exception e) {
44                 // TODO: handle exception
45                 e.printStackTrace();
46             }           
47         }
48          
49         // 下载文件
50         try {
51             url = new URL(remoteUrl);       
52             httpURLConnection = (HttpURLConnection)url.openConnection();
53             // 设置User-Agent
54             httpURLConnection.setRequestProperty("User-Agent", "Net");
55             // 设置续传开始
56             httpURLConnection.setRequestProperty("Range", "bytes=" + nPos + "-");
57             // 获取输入流
58             bis = new BufferedInputStream(httpURLConnection.getInputStream());           
59             rndFile = new RandomAccessFile(filePath + "\\" + fileName, "rw");
60             rndFile.seek(nPos);
61             int i = 0;
62             while ((size = bis.read(buf)) != -1) {
63                 //if (i > 500) break;               
64                 rndFile.write(buf, 0, size);
65                  
66                 i++;
67             }
68             System.out.println("i=" + i);
69             httpURLConnection.disconnect();
70         } catch (Exception e) {
71             // TODO: handle exception
72             e.printStackTrace();
73         }
74     }
75   
76     public static long getRemoteFileSzie(String url) {
77         long size = 0;
78         try {
79             HttpURLConnection httpUrl = (HttpURLConnection)(new URL(url)).openConnection();
80             size = httpUrl.getContentLength();
81             httpUrl.disconnect();           
82         } catch (Exception e) {
83             // TODO: handle exception
84             e.printStackTrace();
85         }
86         return size;
87     }
88 }

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多