打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Java 下载支持断点续传

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

01File 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();

[代码] 客户端下载测试

 
01public 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}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
使用HttpClient实现文件的上传下载
ASP.NET上传文件的几种方法
Java 下载支持断点续传服务端
Java实现的断点续传功能
ASP.NET上传和下载文件的代码(转载)
Java利用HttpURLConnection发送post请求上传文件
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服