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;
/**
 * 文件下载(支持断点续传【迅雷\快车\旋风\Firefox\Chrome】)
 * @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)
   return contentType;
  returnFileName = returnFileName.toLowerCase();
  returnFileName = returnFileName.substring(returnFileName.lastIndexOf(".")+1);
  if (returnFileName.equals("html") || returnFileName.equals("htm") || returnFileName.equals("shtml")){
   contentType = "text/html";
  } else if (returnFileName.equals("css")){
   contentType = "text/css";
  } else if (returnFileName.equals("xml")){
   contentType = "text/xml";
  } else if (returnFileName.equals("gif")){
   contentType = "image/gif";
  } else if (returnFileName.equals("jpeg") || returnFileName.equals("jpg")){
   contentType = "image/jpeg";
  } else if (returnFileName.equals("js")){
   contentType = "application/x-javascript";
  } else if (returnFileName.equals("atom")){
   contentType = "application/atom+xml";
  } else if (returnFileName.equals("rss")){
   contentType = "application/rss+xml";
  } else if (returnFileName.equals("mml")){
   contentType = "text/mathml";
  } else if (returnFileName.equals("txt")){
   contentType = "text/plain";
  } else if (returnFileName.equals("jad")){
   contentType = "text/vnd.sun.j2me.app-descriptor";
  } else if (returnFileName.equals("wml")){
   contentType = "text/vnd.wap.wml";
  } else if (returnFileName.equals("htc")){
   contentType = "text/x-component";
  } else if (returnFileName.equals("png")){
   contentType = "image/png";
  } else if (returnFileName.equals("tif") || returnFileName.equals("tiff")){
   contentType = "image/tiff";
  } else if (returnFileName.equals("wbmp")){
   contentType = "image/vnd.wap.wbmp";
  } else if (returnFileName.equals("ico")){
   contentType = "image/x-icon";
  } else if (returnFileName.equals("jng")){
   contentType = "image/x-jng";
  } else if (returnFileName.equals("bmp")){
   contentType = "image/x-ms-bmp";
  } else if (returnFileName.equals("svg")){
   contentType = "image/svg+xml";
  } else if (returnFileName.equals("jar") || returnFileName.equals("var") || returnFileName.equals("ear")){
   contentType = "application/java-archive";
  } else if (returnFileName.equals("doc")){
   contentType = "application/msword";
  } else if (returnFileName.equals("pdf")){
   contentType = "application/pdf";
  } else if (returnFileName.equals("rtf")){
   contentType = "application/rtf";
  } else if (returnFileName.equals("xls")){
   contentType = "application/vnd.ms-excel";
  } else if (returnFileName.equals("ppt")){
   contentType = "application/vnd.ms-powerpoint";
  } else if (returnFileName.equals("7z")){
   contentType = "application/x-7z-compressed";
  } else if (returnFileName.equals("rar")){
   contentType = "application/x-rar-compressed";
  } else if (returnFileName.equals("swf")){
   contentType = "application/x-shockwave-flash";
  } else if (returnFileName.equals("rpm")){
   contentType = "application/x-redhat-package-manager";
  } else if (returnFileName.equals("der") || returnFileName.equals("pem") || returnFileName.equals("crt")){
   contentType = "application/x-x509-ca-cert";
  } else if (returnFileName.equals("xhtml")){
   contentType = "application/xhtml+xml";
  } else if (returnFileName.equals("zip")){
   contentType = "application/zip";
  } else if (returnFileName.equals("mid") || returnFileName.equals("midi") || returnFileName.equals("kar")){
   contentType = "audio/midi";
  } else if (returnFileName.equals("mp3")){
   contentType = "audio/mpeg";
  } else if (returnFileName.equals("ogg")){
   contentType = "audio/ogg";
  } else if (returnFileName.equals("m4a")){
   contentType = "audio/x-m4a";
  } else if (returnFileName.equals("ra")){
   contentType = "audio/x-realaudio";
  } else if (returnFileName.equals("3gpp") || returnFileName.equals("3gp")){
   contentType = "video/3gpp";
  } else if (returnFileName.equals("mp4") ){
   contentType = "video/mp4";
  } else if (returnFileName.equals("mpeg") || returnFileName.equals("mpg") ){
   contentType = "video/mpeg";
  } else if (returnFileName.equals("mov")){
   contentType = "video/quicktime";
  } else if (returnFileName.equals("flv")){
   contentType = "video/x-flv";
  } else if (returnFileName.equals("m4v")){
   contentType = "video/x-m4v";
  } else if (returnFileName.equals("mng")){
   contentType = "video/x-mng";
  } else if (returnFileName.equals("asx") || returnFileName.equals("asf")){
   contentType = "video/x-ms-asf";
  } else if (returnFileName.equals("wmv")){
   contentType = "video/x-ms-wmv";
  } else if (returnFileName.equals("avi")){
   contentType = "video/x-msvideo";
  }
  return contentType;
 }
 // UTF8转码
 public static String toUtf8String(String s) {
  StringBuffer sb = new StringBuffer();
  int len = s.toCharArray().length;
  for (int i = 0; i < len; i++) {
   char c = s.charAt(i);
   if (c >= 0 && c <= 255) {
    sb.append(c);
   } else {
    byte[] b;
    try {
     b = Character.toString(c).getBytes("utf-8");
    } catch (Exception ex) {
     System.out.println(ex);
     b = new byte[0];
    }
    for (int j = 0; j < b.length; j++) {
     int k = b[j];
     if (k < 0)
      k += 256;
     sb.append("%" + Integer.toHexString(k).toUpperCase());
    }
   }
  }
  String s_utf8 = sb.toString();
  sb.delete(0, sb.length());
  sb.setLength(0);
  sb = null;
  return s_utf8;
 }
 public static InputStream skipFully(InputStream in,long howMany)throws Exception{
 long remainning = howMany;
 long len = 0;
 while(remainning>0){
  len = in.skip(len);
  remainning -= len;
 }
 return in;
 }
}

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

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

(0)

相关推荐

  • 命令行使用支持断点续传的java多线程下载器

    复制代码 代码如下: package org.load.download; import java.io.File;import java.io.IOException;import java.io.InputStream;import java.io.RandomAccessFile;import java.text.DecimalFormat; import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;impo

  • 很简单的Java断点续传实现原理

    原理解析 在开发当中,"断点续传"这种功能很实用和常见,听上去也是比较有"逼格"的感觉.所以通常我们都有兴趣去研究研究这种功能是如何实现的? 以Java来说,网络上也能找到不少关于实现类似功能的资料.但是呢,大多数都是举个Demo然后贴出源码,真正对其实现原理有详细的说明很少. 于是我们在最初接触的时候,很可能就是直接Crtl + C/V代码,然后捣鼓捣鼓,然而最终也能把效果弄出来.但初学时这样做其实很显然是有好有坏的. 好处在于,源码很多,解释很少:如果我们肯下功

  • Java实现的断点续传功能的示例代码

    代码中已经加入了注释,需要的朋友可以直接参考代码中的注释.下面直接上功能实现的主要代码: import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.net.HttpURLConnection; import java.net.Malfor

  • Java如何实现HTTP断点续传功能

    (一)断点续传的原理 其实断点续传的原理很简单,就是在Http的请求上和一般的下载有所不同而已. 打个比方,浏览器请求服务器上的一个文时,所发出的请求如下: 假设服务器域名为wwww.sjtu.edu.cn,文件名为down.zip. GET /down.zip HTTP/1.1 Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms- excel, application/msword, a

  • java断点续传功能实例(java获取远程文件)

    复制代码 代码如下: import java.io.BufferedInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.net . * ; /** * 文件传送客户端:获取远程文件 */ public cl

  • java实现文件断点续传下载功能

    本文实例为大家分享了java断点续传下载的代码,供大家参考,具体内容如下 1. Java代码     //实现文件下载功能 public String downloadFile(){ File dir = new File(filepath);//获取文件路劲 if(!dir.exists()) { System.out.println("文件路径错误"); log.debug("文件路径错误"); return "failed";// 判断文件

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

    本文实例讲述了Java编程实现服务器端支持断点续传的方法.分享给大家供大家参考,具体如下: 大家知道Tomcat之流对静态资源可以实现断点续传支持,但是如果是一个被控制的流,如有权限控制,或下载地址仅是个代理的时候,这时候需要自己实现断点续传的支持,小弟不才,这里提供基本断点续传[a-,-b,a-b]的简单实现,经验证,可支持迅雷7和火狐的多次断点续传.现贴出代码,大家共同分享: Servlet import java.io.BufferedOutputStream; import java.i

  • JAVA编程实现UDP网络通讯的方法示例

    本文实例讲述了JAVA编程实现UDP网络通讯的方法.分享给大家供大家参考,具体如下: UDP协议全称是用户数据报协议,在网络中它与TCP协议一样用于处理数据包,是一种无连接的协议. 在OSI模型中,在第四层--传输层,处于IP协议的上一层.UDP有不提供数据包分组.组装和不能对数据包进行排序的缺点: 也就是说,当报文发送之后,是无法得知其是否安全完整到达的.UDP用来支持那些需要在计算机之间传输数据的网络应用. 采用UDP协议要先把数据定义成数据报(Datagram)并在数据报中指明数据所要达到

  • JAVA编程实现TCP网络通讯的方法示例

    本文实例讲述了JAVA编程实现TCP网络通讯的方法.分享给大家供大家参考,具体如下: TCP(Transmission Control Protocol 传输控制协议)是一种面向连接的.可靠的.基于字节流的传输层通信协议. 由IETF的RFC 793定义,在简化的计算机网络OSI模型中,它完成第四层传输层所指定的功能. 基于TCP网络通讯实现的类主要有服务器端的ServerSocket用客户端的Socket. 通讯流程: 打开服务器,等待客户端连接-->客户端连接上服务器-->数据通讯. 代码

  • Java编程获取当前屏幕分辨率的方法示例

    本文实例讲述了Java编程获取当前屏幕分辨率的方法.分享给大家供大家参考,具体如下: /** * This class implements the functionality of fetching the size of the screen */ package com.leo.util; /** * @author Leo Share * @since 07/16/2007 * @version 1.0 */ class ScreenSize{ private int screenWid

  • java编程实现邮件定时发送的方法

    本文实例讲述了java编程实现邮件定时发送的方法.分享给大家供大家参考,具体如下: 最近做项目时客户提出了一个需求:系统定时发送E-mail到其客户,达到通知的效果.先将实例分享给大家,如果确实有一些帮助的话,请大家来点掌声! 首先介绍java定时器(java.util.Timer)有定时执行计划任务的功能,通过设定定时器的间隔时间,会自动在此间隔时间后执行预先安排好的任务(java.util. TimerTask) 如: 每隔一个小时执行任务 timer.schedule(TimerTask,

  • Java编程获取经纬度之间距离的方法

    本文实例讲述了Java编程获取经纬度之间距离的方法.分享给大家供大家参考,具体如下: public class GeoUtil { /** * 根据经纬度和距离返回一个矩形范围 * * @param lng * 经度 * @param lat * 纬度 * @param distance * 距离(单位为米) * @return [lng1,lat1, lng2,lat2] 矩形的左下角(lng1,lat1)和右上角(lng2,lat2) */ public static double[] ge

  • Java编程调用微信支付功能的方法详解

    本文实例讲述了Java编程调用微信支付功能的方法.分享给大家供大家参考,具体如下: 微信开发文档地址:https://mp.weixin.qq.com/wiki/home/ 从调用处开始 我的流程: 1.点击"支付"按钮,去后台 --> 2.后台生成支付所需数据返回页面 --> 3.页面点击"确认支付"调用微信支付js.完成支付功能. 支付按钮 <div class="button" id="pay" onc

  • Java编程实现调用com操作Word方法实例代码

    实例代码如下: import com.jacob.activeX.ActiveXComponent; import com.jacob.com.Dispatch; import com.jacob.com.Variant; /** * jacob操作MSword类 * @author */ public class WordBean { // word文档 private Dispatch doc; // word运行程序对象 private ActiveXComponent word; //

  • 实例讲解Java编程中数组反射的使用方法

    什么是反射 "反射(Reflection)能够让运行于JVM中的程序检测和修改运行时的行为."这个概念常常会和内省(Introspection)混淆,以下是这两个术语在Wikipedia中的解释: 内省用于在运行时检测某个对象的类型和其包含的属性: 反射用于在运行时检测和修改某个对象的结构及其行为. 从它们的定义可以看出,内省是反射的一个子集.有些语言支持内省,但并不支持反射,如C++. 内省示例:instanceof 运算符用于检测某个对象是否属于特定的类. if (obj inst

  • java编程简单获取图片像素的方法

    本文实例讲述了java获取图片像素的方法.分享给大家供大家参考,具体如下: package cn.net.comsys.sso; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import java.io.*; public class Test { public static void main(String args[]) { File file = new File("a.bmp"); Buf

随机推荐