Java 服务器端支持断点续传的源代码(仅支持 HTTP 协议)

这几天一直在弄断点下载,代码是写好了,断点下载页可以了,就是在客户端点击暂停,或断开连接时,服务器端会报异常:ClientAbortException:  java.net.SocketException: Connection reset by peer: socket write error
这个异常是当客户端断开连接,然后服务器端还在往客户端发送数据,这样就会报这个错,实在是无法搞定这个异常,大家也不用去管它,确实也不影响下载的正常运行。
后面查资料,发现tomcat本身就支持虚拟目录里的静态文件的断点下载功能,这样就好了,不用自己去写代码处理了,哈哈....
在这过程中发现篇文章,写的蛮好的,记录下来:

  • import java.io.BufferedOutputStream;
  • import java.io.File;
  • import java.io.IOException;
  • import java.io.OutputStream;
  • import java.io.RandomAccessFile;
  • import javax.servlet.ServletException;
  • import javax.servlet.http.HttpServlet;
  • import javax.servlet.http.HttpServletRequest;
  • import javax.servlet.http.HttpServletResponse;
  • import org.apache.commons.logging.Log;
  • import org.apache.commons.logging.LogFactory;
  • import com.defonds.cds.common.util.CommonUtil;
  • //HTTP 断点续传 demo(客户端测试工具:快车、迅雷)
  • public class ArcSyncHttpDownloadServlet extends HttpServlet {
  •     private static final long serialVersionUID = 1L;
  •     final static Log log = LogFactory.getLog(ArcSyncHttpDownloadServlet.class);
  •     @Override
  •     protected void doGet(HttpServletRequest req, HttpServletResponse resp)
  •             throws ServletException, IOException {
  •         this.doPost(req, resp);
  •     }
  •     @Override
  •     protected void doPost(HttpServletRequest request, HttpServletResponse response) {
  •         File downloadFile = new File("D:/defonds/book/pattern/SteveJobsZH.pdf");//要下载的文件
  •         long fileLength = downloadFile.length();//记录文件大小
  •         long pastLength = 0;//记录已下载文件大小
  •         int rangeSwitch = 0;//0:从头开始的全文下载;1:从某字节开始的下载(bytes=27000-);2:从某字节开始到某字节结束的下载(bytes=27000-39000)
  •         long toLength = 0;//记录客户端需要下载的字节段的最后一个字节偏移量(比如bytes=27000-39000,则这个值是为39000)
  •         long contentLength = 0;//客户端请求的字节总量
  •         String rangeBytes = "";//记录客户端传来的形如“bytes=27000-”或者“bytes=27000-39000”的内容
  •         RandomAccessFile raf = null;//负责读取数据
  •         OutputStream os = null;//写出数据
  •         OutputStream out = null;//缓冲
  •         byte b[] = new byte[1024];//暂存容器
  •         if (request.getHeader("Range") != null) {// 客户端请求的下载的文件块的开始字节
  •             response.setStatus(javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT);
  •             log.info("request.getHeader("Range")=" + request.getHeader("Range"));
  •             rangeBytes = request.getHeader("Range").replaceAll("bytes=", "");
  •             if (rangeBytes.indexOf('-') == rangeBytes.length() - 1) {//bytes=969998336-
  •                 rangeSwitch = 1;
  •                 rangeBytes = rangeBytes.substring(0, rangeBytes.indexOf('-'));
  •                 pastLength = Long.parseLong(rangeBytes.trim());
  •                 contentLength = fileLength - pastLength + 1;//客户端请求的是 969998336 之后的字节
  •             } else {//bytes=1275856879-1275877358
  •                 rangeSwitch = 2;
  •                 String temp0 = rangeBytes.substring(0,rangeBytes.indexOf('-'));
  •                 String temp2 = rangeBytes.substring(rangeBytes.indexOf('-') + 1, rangeBytes.length());
  •                 pastLength = Long.parseLong(temp0.trim());//bytes=1275856879-1275877358,从第 1275856879 个字节开始下载
  •                 toLength = Long.parseLong(temp2);//bytes=1275856879-1275877358,到第 1275877358 个字节结束
  •                 contentLength = toLength - pastLength + 1;//客户端请求的是 1275856879-1275877358  之间的字节
  •             }
  •         } else {//从开始进行下载
  •             contentLength = fileLength;//客户端要求全文下载
  •         }
  •         response.reset();//告诉客户端允许断点续传多线程连接下载,响应的格式是:Accept-Ranges: bytes
  •         response.setHeader("Accept-Ranges", "bytes");//如果是第一次下,还没有断点续传,状态是默认的 200,无需显式设置;响应的格式是:HTTP/1.1 200 OK
  •         if (pastLength != 0) {
  •             //不是从最开始下载,
  •             //响应的格式是:
  •             //Content-Range: bytes [文件块的开始字节]-[文件的总大小 - 1]/[文件的总大小]
  •             log.info("----------------------------不是从开始进行下载!服务器即将开始断点续传...");
  •             switch (rangeSwitch) {
  •                 case 1 : {//针对 bytes=27000- 的请求
  •                     String contentRange = new StringBuffer("bytes ").append(new Long(pastLength).toString()).append("-").append(new Long(fileLength - 1).toString()).append("/").append(new Long(fileLength).toString()).toString();
  •                     response.setHeader("Content-Range", contentRange);
  •                     break;
  •                 }
  •                 case 2 : {//针对 bytes=27000-39000 的请求
  •                     String contentRange = rangeBytes + "/" + new Long(fileLength).toString();
  •                     response.setHeader("Content-Range", contentRange);
  •                     break;
  •                 }
  •                 default : {
  •                     break;
  •                 }
  •             }
  •         } else {
  •             //是从开始下载
  •             log.info("----------------------------是从开始进行下载!");
  •         }
  •         try {
  •             response.addHeader("Content-Disposition", "attachment; filename="" + downloadFile.getName() + """);
  •             response.setContentType( CommonUtil.setContentType(downloadFile.getName()));// set the MIME type.
  •             response.addHeader("Content-Length", String.valueOf(contentLength));
  •             os = response.getOutputStream();
  •             out = new BufferedOutputStream(os);
  •             raf = new RandomAccessFile(downloadFile, "r");
  •             try {
  •                 switch (rangeSwitch) {
  •                     case 0 : {//普通下载,或者从头开始的下载
  •                         //同1
  •                     }
  •                     case 1 : {//针对 bytes=27000- 的请求
  •                         raf.seek(pastLength);//形如 bytes=969998336- 的客户端请求,跳过 969998336  个字节
  •                         int n = 0;
  •                         while ((n = raf.read(b, 0, 1024)) != -1) {
  •                             out.write(b, 0, n);
  •                         }
  •                         break;
  •                     }
  •                     case 2 : {//针对 bytes=27000-39000 的请求
  •                         raf.seek(pastLength - 1);//形如 bytes=1275856879-1275877358 的客户端请求,找到第 1275856879 个字节
  •                         int n = 0;
  •                         long readLength = 0;//记录已读字节数
  •                         while (readLength <= contentLength - 1024) {//大部分字节在这里读取
  •                             n = raf.read(b, 0, 1024);
  •                             readLength += 1024;
  •                             out.write(b, 0, n);
  •                         }
  •                         if (readLength <= contentLength) {//余下的不足 1024 个字节在这里读取
  •                             n = raf.read(b, 0, (int)(contentLength - readLength));
  •                             out.write(b, 0, n);
  •                         }
  • //
  • //                      raf.seek(pastLength);//形如 bytes=1275856879-1275877358 的客户端请求,找到第 1275856879 个字节
  • //                      while (raf.getFilePointer() < toLength) {
  • //                          out.write(raf.read());
  • //                      }
  •                         break;
  •                     }
  •                     default : {
  •                         break;
  •                     }
  •                 }
  •                 out.flush();
  •             } catch(IOException ie) {
  •                 //ignore
  •             }
  •         } catch (Exception e) {
  •             log.error(e.getMessage(), e);
  •         } finally {
  •             if (out != null) {
  •                 try {
  •                     out.close();
  •                 } catch (IOException e) {
  •                     log.error(e.getMessage(), e);
  •                 }
  •             }
  •             if (raf != null) {
  •                 try {
  •                     raf.close();
  •                 } catch (IOException e) {
  •                     log.error(e.getMessage(), e);
  •                 }
  •             }
  •         }
  •     }
  • }
  • ArcSyncHttpDownloadServlet 调用到的工具类 com.defonds.cds.common.util.CommonUtil 源代码:
  1. public class CommonUtil {
  2.     public static String setContentType(String returnFileName){
  3.         String contentType = "application/octet-stream";
  4.         if (returnFileName.lastIndexOf(".") < 0)
  5.             return contentType;
  6.         returnFileName = returnFileName.toLowerCase();
  7.         returnFileName = returnFileName.substring(returnFileName.lastIndexOf(".")+1);
  8.         if (returnFileName.equals("html") || returnFileName.equals("htm") || returnFileName.equals("shtml")){
  9.             contentType = "text/html";
  10.         } else if (returnFileName.equals("css")){
  11.             contentType = "text/css";
  12.         } else if (returnFileName.equals("xml")){
  13.             contentType = "text/xml";
  14.         } else if (returnFileName.equals("gif")){
  15.             contentType = "image/gif";
  16.         } else if (returnFileName.equals("jpeg") || returnFileName.equals("jpg")){
  17.             contentType = "image/jpeg";
  18.         } else if (returnFileName.equals("js")){
  19.             contentType = "application/x-javascript";
  20.         } else if (returnFileName.equals("atom")){
  21.             contentType = "application/atom+xml";
  22.         } else if (returnFileName.equals("rss")){
  23.             contentType = "application/rss+xml";
  24.         } else if (returnFileName.equals("mml")){
  25.             contentType = "text/mathml";
  26.         } else if (returnFileName.equals("txt")){
  27.             contentType = "text/plain";
  28.         } else if (returnFileName.equals("jad")){
  29.             contentType = "text/vnd.sun.j2me.app-descriptor";
  30.         } else if (returnFileName.equals("wml")){
  31.             contentType = "text/vnd.wap.wml";
  32.         } else if (returnFileName.equals("htc")){
  33.             contentType = "text/x-component";
  34.         } else if (returnFileName.equals("png")){
  35.             contentType = "image/png";
  36.         } else if (returnFileName.equals("tif") || returnFileName.equals("tiff")){
  37.             contentType = "image/tiff";
  38.         } else if (returnFileName.equals("wbmp")){
  39.             contentType = "image/vnd.wap.wbmp";
  40.         } else if (returnFileName.equals("ico")){
  41.             contentType = "image/x-icon";
  42.         } else if (returnFileName.equals("jng")){
  43.             contentType = "image/x-jng";
  44.         } else if (returnFileName.equals("bmp")){
  45.             contentType = "image/x-ms-bmp";
  46.         } else if (returnFileName.equals("svg")){
  47.             contentType = "image/svg+xml";
  48.         } else if (returnFileName.equals("jar") || returnFileName.equals("var") || returnFileName.equals("ear")){
  49.             contentType = "application/java-archive";
  50.         } else if (returnFileName.equals("doc")){
  51.             contentType = "application/msword";
  52.         } else if (returnFileName.equals("pdf")){
  53.             contentType = "application/pdf";
  54.         } else if (returnFileName.equals("rtf")){
  55.             contentType = "application/rtf";
  56.         } else if (returnFileName.equals("xls")){
  57.             contentType = "application/vnd.ms-excel";
  58.         } else if (returnFileName.equals("ppt")){
  59.             contentType = "application/vnd.ms-powerpoint";
  60.         } else if (returnFileName.equals("7z")){
  61.             contentType = "application/x-7z-compressed";
  62.         } else if (returnFileName.equals("rar")){
  63.             contentType = "application/x-rar-compressed";
  64.         } else if (returnFileName.equals("swf")){
  65.             contentType = "application/x-shockwave-flash";
  66.         } else if (returnFileName.equals("rpm")){
  67.             contentType = "application/x-redhat-package-manager";
  68.         } else if (returnFileName.equals("der") || returnFileName.equals("pem") || returnFileName.equals("crt")){
  69.             contentType = "application/x-x509-ca-cert";
  70.         } else if (returnFileName.equals("xhtml")){
  71.             contentType = "application/xhtml+xml";
  72.         } else if (returnFileName.equals("zip")){
  73.             contentType = "application/zip";
  74.         } else if (returnFileName.equals("mid") || returnFileName.equals("midi") || returnFileName.equals("kar")){
  75.             contentType = "audio/midi";
  76.         } else if (returnFileName.equals("mp3")){
  77.             contentType = "audio/mpeg";
  78.         } else if (returnFileName.equals("ogg")){
  79.             contentType = "audio/ogg";
  80.         } else if (returnFileName.equals("m4a")){
  81.             contentType = "audio/x-m4a";
  82.         } else if (returnFileName.equals("ra")){
  83.             contentType = "audio/x-realaudio";
  84.         } else if (returnFileName.equals("3gpp") || returnFileName.equals("3gp")){
  85.             contentType = "video/3gpp";
  86.         } else if (returnFileName.equals("mp4") ){
  87.             contentType = "video/mp4";
  88.         } else if (returnFileName.equals("mpeg") || returnFileName.equals("mpg") ){
  89.             contentType = "video/mpeg";
  90.         } else if (returnFileName.equals("mov")){
  91.             contentType = "video/quicktime";
  92.         } else if (returnFileName.equals("flv")){
  93.             contentType = "video/x-flv";
  94.         } else if (returnFileName.equals("m4v")){
  95.             contentType = "video/x-m4v";
  96.         } else if (returnFileName.equals("mng")){
  97.             contentType = "video/x-mng";
  98.         } else if (returnFileName.equals("asx") || returnFileName.equals("asf")){
  99.             contentType = "video/x-ms-asf";
  100.         } else if (returnFileName.equals("wmv")){
  101.             contentType = "video/x-ms-wmv";
  102.         } else if (returnFileName.equals("avi")){
  103.             contentType = "video/x-msvideo";
  104.         }
  105.         return contentType;
  106.     }
  107. }

(文/gavin的博客

来源:gavin的博客


如果给你带来帮助,欢迎微信或支付宝扫一扫,赞一下。