HttpURLConnection实现文件断点续传

本文介绍了一种基于Java的断点续传实现方案,详细展示了客户端和服务端的代码实现过程,包括设置HTTP请求头、文件流传输以及断点续传的具体实现。

首先

client端:

  1. HttpURLConnection conn = null;  
  2.         BufferedInputStream fin = null;  
  3.         BufferedOutputStream out = null;  
  4.         URL reqUrl;  
  5.         try {  
  6.             reqUrl = new URL("http://<ip>:<port>/Emergency/phone/attachmentUpload");  
  7.             conn = (HttpURLConnection) reqUrl.openConnection();  
  8.             conn.setConnectTimeout(3000);  
  9.             conn.setRequestMethod("PUT");  
  10.             if(isCommit){  
  11.                 conn.setRequestProperty("isCommit""true");  
  12.             }else{  
  13.                 conn.setRequestProperty("isCommit""false");  
  14.             }  
  15.             conn.setRequestMethod("PUT");  
  16.             conn.setRequestProperty("Content-Type""binary/octet-stream");  
  17.             conn.setRequestProperty("offset", StringUtil.toString(offset));  
  18.             conn.setDoOutput(true);  
  19.             conn.setDoInput(true);  
  20.             // 1M的chunk缓冲  
  21.             conn.setChunkedStreamingMode(1024*1024);  
  22.             out = new BufferedOutputStream(conn.getOutputStream());  
  23.             fin = new BufferedInputStream(new FileInputStream(file));  
  24.             byte[] buf = new byte[bufferSizeUpload];  
  25.             int len = -1;  
  26.             long currentUploadSize = offset;  
  27.             fin.skip(offset);  
  28.             while ((len = fin.read(buf)) != -1&currentUploadSize<offset+uploadSize) {  
  29.                 if(offset+uploadSize-currentUploadSize<bufferSizeUpload){  
  30.                     len = Integer.parseInt(StringUtil.toString(offset+uploadSize-currentUploadSize));  
  31.                 }  
  32.                 if(len>0){  
  33.                     if(out!=null){  
  34.                         out.write(buf, 0, len);  
  35.                         out.flush();  
  36.                     }  
  37.                 }  
  38.                 currentUploadSize += len;  
  39.             }  
  40.         } catch (SocketTimeoutException e) {  
  41.             e.printStackTrace();  
  42.         } catch(IOException e){  
  43.             e.printStackTrace();  
  44.         } finally {  
  45.             try {  
  46.                 if (fin != null) {  
  47.                     fin.close();  
  48.                     fin = null;  
  49.                 }  
  50.                 if (out != null) {  
  51.                     out.close();  
  52.                     out = null;  
  53.                 }  
  54.                 if (conn != null) {  
  55.                     conn.disconnect();  
  56.                     conn = null;  
  57.                 }  
  58.             } catch (IOException ioe) {  
  59.                 ioe.printStackTrace();  
  60.                 throw new RuntimeException("Release resource failed.");  
  61.             }  
  62.         }  
HttpURLConnection conn = null;
		BufferedInputStream fin = null;
		BufferedOutputStream out = null;
		URL reqUrl;
		try {
			reqUrl = new URL("http://<ip>:<port>/Emergency/phone/attachmentUpload");
			conn = (HttpURLConnection) reqUrl.openConnection();
			conn.setConnectTimeout(3000);
			conn.setRequestMethod("PUT");
			if(isCommit){
				conn.setRequestProperty("isCommit", "true");
			}else{
				conn.setRequestProperty("isCommit", "false");
			}
			conn.setRequestMethod("PUT");
			conn.setRequestProperty("Content-Type", "binary/octet-stream");
			conn.setRequestProperty("offset", StringUtil.toString(offset));
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 1M的chunk缓冲
			conn.setChunkedStreamingMode(1024*1024);
			out = new BufferedOutputStream(conn.getOutputStream());
			fin = new BufferedInputStream(new FileInputStream(file));
			byte[] buf = new byte[bufferSizeUpload];
			int len = -1;
			long currentUploadSize = offset;
			fin.skip(offset);
			while ((len = fin.read(buf)) != -1&currentUploadSize<offset+uploadSize) {
				if(offset+uploadSize-currentUploadSize<bufferSizeUpload){
					len = Integer.parseInt(StringUtil.toString(offset+uploadSize-currentUploadSize));
				}
				if(len>0){
					if(out!=null){
						out.write(buf, 0, len);
						out.flush();
					}
				}
				currentUploadSize += len;
			}
		} catch (SocketTimeoutException e) {
			e.printStackTrace();
		} catch(IOException e){
			e.printStackTrace();
		} finally {
			try {
				if (fin != null) {
					fin.close();
					fin = null;
				}
				if (out != null) {
					out.close();
					out = null;
				}
				if (conn != null) {
					conn.disconnect();
					conn = null;
				}
			} catch (IOException ioe) {
				ioe.printStackTrace();
				throw new RuntimeException("Release resource failed.");
			}
		}

如上所示:url参数通过setRequestProperty方法放在请求头中 ,而文件流放在 body 中。

同时需要注意 HttpURLConnection.setChunkedStreamingMode 此方法保证每次文件流达到指定大小就发送一次,避免了放在缓存并一次性传输中可能遇到的数据缺失。

http://blog.youkuaiyun.com/z69183787/article/details/8186918 可参考


服务端:

  1. public String underUpload() throws IOException{  
  2.         String data = request.getHeader("data");   
  3.         String userInfo = request.getHeader("userInfo");   
  4.         userInfo = new String(userInfo.getBytes("iso-8859-1"),"GBK");  
  5.         //System.out.println(data);  
  6.         //System.out.println(userInfo);  
  7.         Map<String,String> data_map = gson.fromJson(data,attachVo.data_map.getClass());  
  8.         if(data_map!=null) attachVo.data_map=data_map;  
  9.         attachVo.user = gson.fromJson(userInfo,attachVo.user.getClass());  
  10.         apiService.attachUpload(attachVo,new BufferedInputStream(request.getInputStream()));  
  11.         //response.setStatus(200);  
  12.         return null;  
  13.     }  
public String underUpload() throws IOException{
		String data = request.getHeader("data"); 
		String userInfo = request.getHeader("userInfo"); 
		userInfo = new String(userInfo.getBytes("iso-8859-1"),"GBK");
		//System.out.println(data);
		//System.out.println(userInfo);
		Map<String,String> data_map = gson.fromJson(data,attachVo.data_map.getClass());
		if(data_map!=null) attachVo.data_map=data_map;
		attachVo.user = gson.fromJson(userInfo,attachVo.user.getClass());
		apiService.attachUpload(attachVo,new BufferedInputStream(request.getInputStream()));
		//response.setStatus(200);
		return null;
	}

使用的是ssh架构 ,通过getHeader 得到 url参数,通过getInputStream得到文件流,同时还要控制好编码,以防中文乱码。


至于断点续传,基本思想是通过信息头的部分 传递每次传输的文件大小,与服务器端的文件大小匹配。并通过

  1. RandomAccessFile raFile = new RandomAccessFile(uploadFile.getAbsolutePath(), "rw");  
  2.         raFile.seek(uploadFile.length());  
RandomAccessFile raFile = new RandomAccessFile(uploadFile.getAbsolutePath(), "rw");
		raFile.seek(uploadFile.length());

方法进行根据传输大小实时进行文件读写。


  1. public static void saveFile(String destFilePathStr,String destFileName){  
  2.         try {  
  3.             File destFilePath = new File(destFilePathStr);  
  4.             if(!destFilePath.exists()){  
  5.                 destFilePath.mkdirs();  
  6.                 destFilePath = null;  
  7.             }  
  8.             File destFile = new File(destFilePathStr+"//"+destFileName);  
  9.             if(!destFile.exists()){  
  10.                 destFile.createNewFile();  
  11.             }  
  12.       
  13.         } catch (Exception e) {  
  14.             e.printStackTrace();  
  15.         }  
  16.     }  
  17.       
  18.     public static long uploadFile(String offset,String destFileName,BufferedInputStream bis)   
  19.     throws IOException{  
  20.         File uploadFile = new File(destFileName);  
  21.         int len = 0;  
  22.         byte[] bt = new byte[1024];  
  23.         RandomAccessFile raFile = new RandomAccessFile(uploadFile.getAbsolutePath(), "rw");  
  24.         raFile.seek(uploadFile.length());  
  25.         while ((len = bis.read(bt)) > 0){  
  26.             raFile.write(bt, 0, len);  
  27.         }  
  28.         long l = raFile.length();  
  29.         try {  
  30.              if(bis != null)  
  31.                  bis.close();  
  32.              if (raFile != null)  
  33.                  raFile.close();  
  34.                
  35.         } catch (IOException e) {  
  36.             l = 0;  
  37.             e.printStackTrace();  
  38.         }  
  39.         return l ;  
  40.     }  
public static void saveFile(String destFilePathStr,String destFileName){
		try {
			File destFilePath = new File(destFilePathStr);
			if(!destFilePath.exists()){
				destFilePath.mkdirs();
				destFilePath = null;
			}
			File destFile = new File(destFilePathStr+"//"+destFileName);
			if(!destFile.exists()){
				destFile.createNewFile();
			}
	
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static long uploadFile(String offset,String destFileName,BufferedInputStream bis) 
	throws IOException{
		File uploadFile = new File(destFileName);
		int len = 0;
		byte[] bt = new byte[1024];
		RandomAccessFile raFile = new RandomAccessFile(uploadFile.getAbsolutePath(), "rw");
		raFile.seek(uploadFile.length());
	    while ((len = bis.read(bt)) > 0){
	    	raFile.write(bt, 0, len);
    	}
	    long l = raFile.length();
	    try {
		     if(bis != null)
		    	 bis.close();
		     if (raFile != null)
		    	 raFile.close();
		     
		} catch (IOException e) {
			l = 0;
		    e.printStackTrace();
		}
		return l ;
	}

首先创建一个空文件,接下来根据每次接收的文件流及文件长度 写入文件。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值