`
aasonwu
  • 浏览: 35224 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

基于html5 websocket API简单实现断点上传文件

 
阅读更多

本实例只是简单地实现文件的断点上传功能,有更好的建议请不吝赐教


本实例基于html5的 websocket API和netty框架,如果您对两个技术不太熟悉,可以点击下面连接了解

websocket: http://www.chinaz.com/web/2012/0806/267188.shtml

http://www.websocket.org/

netty: https://netty.io/

netty jar包:http://download.csdn.net/detail/wudasong_/4650052

准备:

fiefox浏览器或chrome浏览器

在classpath中导入netty类库,json类库

好拉,一切准备就绪...

服务器端:

WebSocketServerInitializer.java

/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.wudasong.breakPoinUploadServer;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.socket.nio.NioEventLoop;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * A HTTP server which serves Web Socket requests at:
 *
 * http://localhost:8080/websocket
 *
 * Open your browser at http://localhost:8080/, then the demo page will be loaded and a Web Socket connection will be
 * made automatically.
 *
 * This server illustrates support for the different web socket specification versions and will work with:
 *
 * <ul>
 * <li>Safari 5+ (draft-ietf-hybi-thewebsocketprotocol-00)
 * <li>Chrome 6-13 (draft-ietf-hybi-thewebsocketprotocol-00)
 * <li>Chrome 14+ (draft-ietf-hybi-thewebsocketprotocol-10)
 * <li>Chrome 16+ (RFC 6455 aka draft-ietf-hybi-thewebsocketprotocol-17)
 * <li>Firefox 7+ (draft-ietf-hybi-thewebsocketprotocol-10)
 * <li>Firefox 11+ (RFC 6455 aka draft-ietf-hybi-thewebsocketprotocol-17)
 * </ul>
 */
public class WebSocketServer {

    private final int port;

    public WebSocketServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        ServerBootstrap b = new ServerBootstrap();
        try {
            b.eventLoop(new NioEventLoop(), new NioEventLoop())
             .channel(new NioServerSocketChannel())
             .localAddress(port)
             .childHandler(new WebSocketServerInitializer());

            Channel ch = b.bind().sync().channel();
            System.out.println("Web socket server started at port " + port + '.');
            System.out.println("Open your browser and navigate to http://localhost:" + port + '/');

            ch.closeFuture().sync();
        } finally {
            b.shutdown();
        }
    }

    public static void main(String[] args) throws Exception {
        int port;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        } else {
            port = 8082;
        }
        new WebSocketServer(port).run();
    }
}

WebSocketServerHandler.java

package com.wudasong.breakPoinUploadServer;

import static io.netty.handler.codec.http.HttpHeaders.*;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpMethod.*;
import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpVersion.*;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import org.json.JSONException;
import org.json.JSONObject;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundMessageHandlerAdapter;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
import io.netty.util.CharsetUtil;

/**
 * Handles handshakes and messages
 */
public class WebSocketServerHandler extends ChannelInboundMessageHandlerAdapter<Object> {

	private static final String WEBSOCKET_PATH = "/websocket";

	private static final long BLOCK_SIZE=1024*65L;
	private static final int BYTE_BUFFER_SIZE=1024*65;
	private static final String SERVER_SAVE_PATH="D:\\fileUpload\\";

	private long startByte=0;
	private long stopByte=0;
	private JSONObject fileInfo;
	private WebSocketServerHandshaker handshaker;

	@Override
	public void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
		if (msg instanceof HttpRequest) {
			handleHttpRequest(ctx, (HttpRequest) msg);
		} else if (msg instanceof WebSocketFrame) {
			handleWebSocketFrame(ctx, (WebSocketFrame) msg);
		}
	}

	private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest req) throws Exception {
		// Allow only GET methods.
		if (req.getMethod() != GET) {
			sendHttpResponse(ctx, req, new DefaultHttpResponse(HTTP_1_1, FORBIDDEN));
			return;
		}
		// Handshake
		WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
				getWebSocketLocation(req), null, false,1048576);
		handshaker = wsFactory.newHandshaker(req);
		if (handshaker == null) {
			wsFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel());
		} else {
			handshaker.handshake(ctx.channel(), req);
		}
	}

	private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) throws JSONException, IOException {

		// Check for closing frame
		if (frame instanceof CloseWebSocketFrame) {
			handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame);
			return;
		} else if(frame instanceof TextWebSocketFrame){
			TextWebSocketFrame message=(TextWebSocketFrame)frame;
			fileInfo=new JSONObject(message.getText());
			System.out.println("上传的文件名:\t"+fileInfo.getString("name")+
					"\n文件大小:\t"+fileInfo.getLong("size")+
					"\n最后修改时间:\t"+fileInfo.getString("lastModifiedDate"));
			JSONObject message4client=new JSONObject();
			File file = new File(SERVER_SAVE_PATH+fileInfo.getString("name"));
			long fileSize=fileInfo.getLong("size");
			if(file.createNewFile()){
				stopByte=BLOCK_SIZE;
				message4client.put("startByte", 0);
				if(stopByte<fileSize){
					message4client.put("stopByte", stopByte);
				}else {
					message4client.put("stopByte", fileSize);
				}
				message4client.put("complete", false);
			}else {
				startByte=file.length();
				stopByte=startByte+BLOCK_SIZE;
				if(startByte>=fileInfo.getLong("size")){
					message4client.put("startByte", 0);
					message4client.put("stopByte", 0);
					message4client.put("complete", true);
				}
				if(stopByte<fileSize){
					message4client.put("startByte", startByte);
					message4client.put("stopByte", stopByte);
					message4client.put("complete", false);
				}else {
					message4client.put("startByte", startByte);
					message4client.put("stopByte", fileSize);
					message4client.put("complete", false);
				}
			}
			ctx.channel().write(new TextWebSocketFrame(message4client.toString()));
		}else if(frame instanceof BinaryWebSocketFrame){
			BinaryWebSocketFrame binaryFrame=(BinaryWebSocketFrame)frame;
			File file = new File(SERVER_SAVE_PATH+fileInfo.getString("name"));
			long fileSize=fileInfo.getLong("size");
			if(stopByte>=fileSize){
				stopByte=fileSize;
			}
			JSONObject message4client=new JSONObject();
			if(startByte>=fileInfo.getLong("size")){
				message4client.put("startByte", 0);
				message4client.put("stopByte", 0);
				message4client.put("complete", true);
				ctx.channel().write(new TextWebSocketFrame(message4client.toString()));
			}
			FileChannel fileChannel=new RandomAccessFile(file, "rw").getChannel();
			fileChannel.position(fileChannel.size());


			if(stopByte<fileSize){
				ByteBuffer byteBuffer=ByteBuffer.allocate(BYTE_BUFFER_SIZE);
				byteBuffer.clear();
				byteBuffer.put(binaryFrame.getBinaryData().array());
				byteBuffer.flip();
				fileChannel.write(byteBuffer);
				fileChannel.close();
				startByte=stopByte;
				stopByte=startByte+BLOCK_SIZE;
				message4client.put("startByte", startByte);
				message4client.put("stopByte", stopByte);
				message4client.put("complete", false);
				ctx.channel().write(new TextWebSocketFrame(message4client.toString()));
			}else {
				ByteBuffer byteBuffer=ByteBuffer.allocate(binaryFrame.getBinaryData().capacity());
				byteBuffer.clear();
				byteBuffer.put(binaryFrame.getBinaryData().array());
				byteBuffer.flip();
				fileChannel.write(byteBuffer);
				fileChannel.close();
				message4client.put("startByte", 0);
				message4client.put("stopByte", 0);
				message4client.put("complete", true);
				ctx.channel().write(new TextWebSocketFrame(message4client.toString()));
			}
		}
	}

	private static void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, HttpResponse res) {
		// Generate an error page if response status code is not OK (200).
		if (res.getStatus().getCode() != 200) {
			res.setContent(Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8));
			setContentLength(res, res.getContent().readableBytes());
		}

		// Send the response and close the connection if necessary.
		ChannelFuture f = ctx.channel().write(res);
		if (!isKeepAlive(req) || res.getStatus().getCode() != 200) {
			f.addListener(ChannelFutureListener.CLOSE);
		}
	}

	private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
		HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
		response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
		response.setContent(Unpooled.copiedBuffer(
				"Failure: " + status.toString() + "\r\n",
				CharsetUtil.UTF_8));
		ctx.write(response).addListener(ChannelFutureListener.CLOSE);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}

	private static String getWebSocketLocation(HttpRequest req) {
		return "ws://" + req.getHeader(HttpHeaders.Names.HOST) + WEBSOCKET_PATH;
	}
}

WebServerSocket.java

/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.wudasong.breakPoinUploadServer;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.socket.nio.NioEventLoop;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * A HTTP server which serves Web Socket requests at:
 *
 * http://localhost:8080/websocket
 *
 * Open your browser at http://localhost:8080/, then the demo page will be loaded and a Web Socket connection will be
 * made automatically.
 *
 * This server illustrates support for the different web socket specification versions and will work with:
 *
 * <ul>
 * <li>Safari 5+ (draft-ietf-hybi-thewebsocketprotocol-00)
 * <li>Chrome 6-13 (draft-ietf-hybi-thewebsocketprotocol-00)
 * <li>Chrome 14+ (draft-ietf-hybi-thewebsocketprotocol-10)
 * <li>Chrome 16+ (RFC 6455 aka draft-ietf-hybi-thewebsocketprotocol-17)
 * <li>Firefox 7+ (draft-ietf-hybi-thewebsocketprotocol-10)
 * <li>Firefox 11+ (RFC 6455 aka draft-ietf-hybi-thewebsocketprotocol-17)
 * </ul>
 */
public class WebSocketServer {

    private final int port;

    public WebSocketServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        ServerBootstrap b = new ServerBootstrap();
        try {
            b.eventLoop(new NioEventLoop(), new NioEventLoop())
             .channel(new NioServerSocketChannel())
             .localAddress(port)
             .childHandler(new WebSocketServerInitializer());

            Channel ch = b.bind().sync().channel();
            System.out.println("Web socket server started at port " + port + '.');
            System.out.println("Open your browser and navigate to http://localhost:" + port + '/');

            ch.closeFuture().sync();
        } finally {
            b.shutdown();
        }
    }

    public static void main(String[] args) throws Exception {
        int port;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        } else {
            port = 8082;
        }
        new WebSocketServer(port).run();
    }
}


客户端代码:

MyHtml.html

<!DOCTYPE html>
<html>
<head>
<title>MyHtml.html</title>

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">


</head>

<body>
	<input type="file" id="files" name="file" />
	<input type="button" id="upload" value="上传" />
	<input type="button" id="stop" value="暂停" />
	<script type="text/javascript" src="upload.js"></script>
</body>
</html>

upload.js

var socket;
//openSocket("ws://localhost:8082/websocket");

document.getElementById("stop").addEventListener("click", function(){
	socket.close();
}, false);

document.getElementById("upload").addEventListener("click", function(){
	openSocket("ws://localhost:8082/websocket");
	setTimeout(function(){
		fileUpload();
	}, 500);
}, false);

function openSocket(url){
	if(!window.WebSocket){
		window.WebSocket=window.MozWebSocket;
	} 
	if(window.WebSocket){
		socket=new WebSocket(url);
//		socket=new WebSocket("ws://localhost:8082/websocket");
		socket.onopen=onOpen;
		socket.onclose=onClose;
	}else {
		alert("your browser does not support websocket");
	}
};

function onOpen(event){
	console.log("websocket is opened");
}

function onClose(event){
	console.log("websocket is closed");
}

function fileUpload(){
	var files = document.getElementById('files').files;
	if (!files.length) {
		alert('Please select a file!');
		return;
	}
	var file = files[0];
	var fileInfo={
			"opcode":1,
			"name":file.name,
			"size":file.size,
			"lastModifiedDate":file.lastModifiedDate
	};
//	console.log(JSON.stringify(fileInfo));
	send(JSON.stringify(fileInfo));
	socket.onmessage=function(event){
		var startStop=JSON.parse(event.data);
		if(startStop.startByte===startStop.stopByte||startStop.complete){
			console.log(startStop);
			alert("文件上传成功!");
		}else {
			console.log(startStop);
			readBlob(files,startStop.startByte, startStop.stopByte);
		}
	};
}

function send(message){
	if(!window.WebSocket){
		return;
	}
	if(socket.readyState==WebSocket.OPEN){
		socket.send(message);
	}else{
		console.log("the socket is not open");
	}
}

function readBlob(files,opt_startByte, opt_stopByte) {
	if (!files.length) {
		alert('Please select a file!');
		return;
	}
	var file = files[0];
	var start = parseInt(opt_startByte) || 0;
	var stop = parseInt(opt_stopByte) || file.size - 1;

	var reader = new FileReader();
	if (file.webkitSlice) {
		var blob = file.webkitSlice(start, stop);
	} else if (file.mozSlice) {
		var blob = file.mozSlice(start, stop);
	}
	reader.readAsArrayBuffer(blob);
	reader.onloadend = function(evt) {
		if (evt.target.readyState == FileReader.DONE) { // DONE == 2
			send(reader.result);
		}
	};
}

搞定..

求多多指教!!

分享到:
评论

相关推荐

    表单文件上传(更新)

    常见的实现方式有Chunked Transfer Encoding或者基于Websocket的断点续传。 **表单文件上传**通常指的是将文件上传与表单数据一起发送到服务器。在HTML中,`&lt;form&gt;`标签的`enctype`属性设置为`multipart/form-data`...

    简单的文件上传(smartupload)

    不过,随着前端技术的发展,现代Web应用更多地倾向于使用基于HTML5的File API和axios等库来处理文件上传,它们提供了更多的控制和更好的跨平台兼容性,但SmartUpload对于一些老项目或者基于Java的服务器端应用仍然是...

    仿163网盘无刷新文件上传系统

    【描述】"仿163网盘无刷新文件上传系统"进一步强调了我们的目标是模仿网易163网盘的功能特性,特别是其基于Ajax或Websocket等技术实现的无刷新上传功能。这种技术的实现需要前端与后端的紧密配合,确保数据传输的...

    大文件上传

    实现多文件上传通常需要用到HTML5的File API,该API提供了在浏览器端处理文件的能力,包括读取、写入和上传。用户可以选择多个文件,然后通过JavaScript处理这些文件,将它们分批或一起上传到服务器。为了优化用户...

    文件批量上传源码 down_51vip_com_文件批量上传客户端免费组件v1.0.3forasp

    《文件批量上传技术详解——基于ASP的实现与优化》 在现代互联网应用中,文件上传功能是不可或缺的一部分,尤其在大数据时代,用户可能需要一次性上传大量文件,这就对文件批量上传技术提出了更高的要求。本文将...

    文件上传问题

    这些技术通常需要在客户端和服务器端实现更复杂的逻辑,例如使用WebSocket进行实时通信,或者利用HTML5的File API。 在实际开发中,我们还会用到一些工具和库,如Resumable.js(JavaScript实现的断点续传库)、Tus...

    HTML5程序设计源码

    另外,`XMLHttpRequest2`也增强了异步请求功能,支持断点续传、文件上传等特性。 地理信息方面,HTML5的`Geolocation API`允许网页获取用户的地理位置信息,这在本地服务、导航应用中非常有用。通过`navigator....

    swfupload实例(java能运行)

    2. 配置HTML:在HTML页面中添加SWFUpload的初始化脚本,设置上传URL、文件类型限制、最大上传文件大小等参数。 3. 创建Java后台接口:根据设置的上传URL,编写对应的Servlet或Controller处理文件上传请求,接收上传...

    上传数据到web服务器

    在IT行业中,将数据上传到Web服务器是一项基本且至关重要的任务,这通常涉及到网页表单提交、API接口交互以及文件传输。以下是一些关于“上传数据到Web服务器”的关键知识点: 1. **HTTP协议**:HTTP(超文本传输...

    uploadfile:nodejs简易上传图片

    总结一下,"uploadfile:nodejs简易上传图片"项目展示了如何使用Node.js和Express搭建一个简单的文件上传服务,前端利用HTML5的FormData和fetch API实现文件上传。在实际开发中,还需要考虑文件安全、性能优化以及...

    HTTP上传下载

    5. **安全性**:为了防止恶意文件上传,服务器通常会对上传文件进行检查,如检查文件类型、大小、是否存在病毒等。 **HTTP下载** HTTP下载则是从服务器获取文件到本地的过程,通常包括以下步骤: 1. **GET请求**...

    luckytuan-fast-loader-master.zip

    基于这些信息,我们可以推测"LuckyTuan Fast Loader"是一个专注于大文件分片上传的工具,可能包括以下关键知识点: 1. **文件分片技术**:理解如何将大文件分割成多个小部分,每个部分独立上传,然后在服务器端重新...

    一个QQ的实现方法

    文件传输可能结合FTP或HTTP上传下载,有时还需要进行文件分块和断点续传以优化大文件传输。 最后,用户体验是QQ成功的关键因素,这需要考虑UI/UX设计原则,包括响应式设计以适应不同设备,以及无障碍性以满足各类...

    meteor-file-uploader:不使用 DDP 的流星的简单文件上传器

    使用"meteor-file-uploader",开发者可以利用HTML5的File API和Ajax技术,将文件分块上传,显著降低了对网络带宽和服务器内存的需求。此外,它还支持断点续传,即使在上传过程中发生中断,也能从上次中断的位置继续...

    网页版聊天程序--网络程序设计课程大作业

    JavaScript是浏览器端的核心脚本语言,它实现了页面的动态交互,包括注册、登录表单验证、消息的即时显示、文件上传进度条以及断点续传功能。在JavaScript中,可能使用了AJAX技术来实现异步通信,确保用户在发送消息...

    MyDropBox:MyDropBox 项目是一个基于云的文件存储

    1. **文件上传**:用户可以通过选择本地文件或直接拖放到界面上来上传文件。这一过程通常涉及到HTML5的File API,它可以读取、操作和上传用户的文件。同时,为了优化用户体验,可能还会使用分块上传技术,将大文件...

    sping+hibernate+struts项目

    1. **文件上传**:使用Servlet或Struts的上传组件处理文件上传,处理大文件分块、断点续传等复杂场景。 2. **文件下载**:提供安全的文件下载链接,支持下载速度限制和文件预览。 3. **目录管理**:创建、删除、...

    JAVA上百实例源码以及开源项目源代码

    凯撒加密解密程序 1个目标文件 1、程序结构化,用函数分别实现 2、对文件的加密,解密输出到文件 利用随机函数抽取幸运数字 简单 EJB的真实世界模型(源代码) 15个目标文件 摘要:Java源码,初学实例,基于EJB的真实...

    python入门到高级全栈工程师培训 第3期 附课件代码

    04 Form组件上传文件 05 上传相关内容梳理 06 Model操作知识提问 07 Model操作概述 08 Model字段 09 Model连表字段参数详解 10 Model自定义多对多第三张表 11 强插一道面试题 12 Model连表操作梳理 13 多对多自关联 ...

    Filez:peer2peer文件传输应用程序

    Filez是一款基于peer-to-peer(P2P)技术的文件传输应用程序,它的设计目标是让用户能够高效、便捷地分享大文件。在P2P网络中,文件不是通过中心服务器进行传输,而是直接由网络中的各个参与者(即对等节点)之间...

Global site tag (gtag.js) - Google Analytics