Java编程实现服务器端支持断点续传的方法(可支持快车、迅雷)

这篇文章主要介绍了Java编程实现服务器端支持断点续传的方法,涉及Java文件传输的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了Java编程实现服务器端支持断点续传的方法分享给大家供大家参考,具体如下:

大家知道Tomcat之流对静态资源可以实现断点续传支持,但是如果是一个被控制的流,如有权限控制,或下载地址仅是个代理的时候,这时候需要自己实现断点续传的支持,小弟不才,这里提供基本断点续传[a-,-b,a-b]的简单实现,经验证,可支持迅雷7和火狐的多次断点续传。现贴出代码,大家共同分享

Servlet

import java.io.bufferedoutputstream; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLDecoder; import javax.servlet.servletexception; import javax.servlet.ServletoutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.bsteel.cloud.storage.servlet.base.BaseServlet; import com.bsteel.cloud.storage.utils.FileUtil; /** * 文件下载(支持断点续传【迅雷快车旋风FirefoxChrome】) * @author jdkleo * */ public class FileIoServlet extends BaseServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws servletexception, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws servletexception, IOException{ download(request,response); } /** * 文件下载 * @param request * @param response * @throws UnsupportedEncodingException */ private void download(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException { File downloadFile = getFile(request); long pos = FileUtil.headerSetting(downloadFile, request, response); // log.info("跳过"+pos); ServletoutputStream os = null; bufferedoutputstream out = null; RandomAccessFile raf = null; byte b[] = new byte[1024];//暂存容器 try { os = response.getoutputStream(); out = new bufferedoutputstream(os); raf = new RandomAccessFile(downloadFile, "r"); raf.seek(pos); try { int n = 0; while ((n = raf.read(b, 0, 1024)) != -1) { out.write(b, 0, n); } out.flush(); } catch(IOException ie) { } } 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); } } } } private File getFile(HttpServletRequest request) throws UnsupportedEncodingException { String uriStr = request.getParameter("uri"); if (null != uriStr){ uriStr = URLDecoder.decode(uriStr,"UTF-8"); if (uriStr.startsWith("file://")){ uriStr = uriStr.substring(7); return new File(uriStr); }else if (uriStr.startsWith("hbase://")){ try { return new File(new URI(uriStr)); } catch (URISyntaxException e) { log.error(e.getMessage(),e); } } } throw new RuntimeException("it's not a real uri"); } }

Range支持

import java.io.File; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 文件处理工具 * @author jdkleo * */ public class FileUtil { /** * 断点续传支持 * @param file * @param request * @param response * @return 跳过多少字节 */ public static long headerSetting(File file,HttpServletRequest request, HttpServletResponse response) { long len = file.length();//文件长度 if ( null == request.getHeader("Range") ){ setResponse(new RangeSettings(len),file.getName(),response); return 0; } String range = request.getHeader("Range").replaceAll("bytes=", ""); RangeSettings settings = getSettings(len,range); setResponse(settings,file.getName(),response); return settings.getStart(); } private static void setResponse(RangeSettings settings,String fileName, HttpServletResponse response) { response.addheader("Content-disposition", "attachment; filename="" + IoUtil.toUtf8String(fileName) + """); response.setContentType( IoUtil.setContentType(fileName));// set the MIME type. if (!settings.isRange()) { response.addheader("Content-Length", String.valueOf(settings.getTotalLength())); } else { long start = settings.getStart(); long end = settings.getEnd(); long contentLength = settings.getContentLength(); response.setStatus(javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT); response.addheader("Content-Length", String.valueOf(contentLength)); String contentRange = new StringBuffer("bytes ").append(start).append("-").append(end).append("/").append(settings.getTotalLength()).toString(); response.setHeader("Content-Range", contentRange); } } private static RangeSettings getSettings(long len, String range) { long contentLength = 0; long start = 0; long end = 0; if (range.startsWith("-"))// -500,最后500个 { contentLength = Long.parseLong(range.substring(1));//要下载的量 end = len-1; start = len - contentLength; } else if (range.endsWith("-"))//从哪个开始 { start = Long.parseLong(range.replace("-", "")); end = len -1; contentLength = len - start; } else//从a到b { String[] se = range.split("-"); start = Long.parseLong(se[0]); end = Long.parseLong(se[1]); contentLength = end-start+1; } return new RangeSettings(start,end,contentLength,len); } }

Range封装

public class RangeSettings{ private long start; private long end; private long contentLength; private long totalLength; private boolean range; public RangeSettings(){ super(); } public RangeSettings(long start, long end, long contentLength,long totalLength) { this.start = start; this.end = end; this.contentLength = contentLength; this.totalLength = totalLength; this.range = true; } public RangeSettings(long totalLength) { this.totalLength = totalLength; } public long getStart() { return start; } public void setStart(long start) { this.start = start; } public long getEnd() { return end; } public void setEnd(long end) { this.end = end; } public long getContentLength() { return contentLength; } public void setContentLength(long contentLength) { this.contentLength = contentLength; } public long getTotalLength() { return totalLength; } public void setTotalLength(long totalLength) { this.totalLength = totalLength; } public boolean isRange() { return range; } }

IO流相关处理工具类

import java.io.InputStream; public class IoUtil { public static String setContentType(String returnFileName){ String contentType = "application/octet-stream"; if (returnFileName.lastIndexOf(".") = 0 && c 0){ len = in.skip(len); remainning -= len; } return in; } }

注有些类比如IoUtil方法来自于CSDN的网友总结,另外此类还不支持多Range配置如[a-b,c-d,-e]等。

希望本文所述对大家Java程序设计有所帮助。

相关文章

HashMap是Java中最常用的集合类框架,也是Java语言中非常典型...
在EffectiveJava中的第 36条中建议 用 EnumSet 替代位字段,...
介绍 注解是JDK1.5版本开始引入的一个特性,用于对代码进行说...
介绍 LinkedList同时实现了List接口和Deque接口,也就是说它...
介绍 TreeSet和TreeMap在Java里有着相同的实现,前者仅仅是对...
HashMap为什么线程不安全 put的不安全 由于多线程对HashMap进...