`
haoningabc
  • 浏览: 1447065 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

websocket上传文件

阅读更多
nginx的上传
查看http://haoningabc.iteye.com/blog/2344484
效果如图

这几天有个需求
上传大文件,需要带进度条,
nginx这个版本有7,8年了,担心有bug,不如用websocket重新写一个
原理
使用websocket.jar
前端需要分片,把一定字节的用websocket传过去
后端用流顺序写到文件里面
(理论上,如果用session把当前存的字节数就可以断点续传)
html代码如下:
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Chat Client</title>
<meta charset="utf-8" />
<script type="text/javascript" src="jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="jquery.json-2.3.js"></script>
<script type="text/javascript">
    $().ready(
            function() {
          if (window.File && window.FileReader && window.FileList
                        && window.Blob) {
                } else {
                    alert('The File APIs are not fully supported in this browser.');
                }
            });

    //在消息框中打印内容
    function log(text) {
        $("#log").append(text+"\n");
    }

    //全局的websocket变量
	var ws;
    var paragraph = 10485760;
    //var paragraph = 1024;
    var fileList ;
    var file;
    var startSize,endSize = 0;
    var i = 0; j = 0;
    //连接服务器
	$(function() {
	    $("#connect").click(function() {
	        ws = new WebSocket($("#uri").val());
	        //连接成功建立后响应
	        ws.onopen = function() {
	            log("成功连接到" + $("#uri").val());
	        }
	        //收到服务器消息后响应
	        
	        ws.onmessage = function(e) {
	            console.log("iiiiiiiiii:"+i);
	            log("服务器说" + e.data + " "+(e.data=="ok"));
	            if((e.data+"") == "ok"){
		            if(endSize < file.size){
			            console.log("file.size:"+file.size);
		            	
		                startSize = endSize;
		                endSize += paragraph ;
		                console.log("startSize:"+startSize);
		                console.log("endSize:"+endSize);
		                console.log("file---haha----:"+file);
		                document.getElementById('progress').innerHTML=Math.round(startSize / file.size * 10000) / 100.00 + "%";
		                if (file.webkitSlice) {
							console.log("webkitSlice--->");
							var blob = file.webkitSlice(startSize, endSize);
		                } else if (file.mozSlice) {
		                	console.log("mozSlice--->");
							var blob = file.mozSlice(startSize, endSize);
		                }else {
		                	console.log("Slice--->");
							var blob = file.slice(startSize, endSize);
		                }
		                var reader = new FileReader();
		                reader.readAsArrayBuffer(blob);
		                reader.onload = function loaded(evt) {
		                    var ArrayBuffer = evt.target.result;
		                    log("发送文件第" + (i++) + "部分");
		                    ws.send(ArrayBuffer);
	                    }
	            	}else{
	            	    console.log("endSize >= file.size-->"+e.data+"<---");
	            	    console.log("endSize >= file.size-->endSize:"+endSize);
	            	    console.log("endSize >= file.size-->file.size:"+file.size);
	                    startSize = endSize = 0;
	                    i = 0;
	                    log("发送" + file.name +"完毕");
	                    log("发送文件完毕");
	            }
	        }
	        //连接关闭后响应
	        ws.onclose = function() {
	            log("关闭连接");
	            ws = null;
	        }
	        return false;
	        }
	    });
	});
    $(function() {
        $("#sendFileForm").click(function() {
            fileList = document.getElementById("file").files;
            file = fileList[0];
            ws.send(file.name);
            
        })
    });
    $(function() {
	    $("#reset").click(function() {
	        $("#log").empty();
	         return false;
	    });
    });
</script>
</head>
<body>
    <span>上传的百分比</span>
    <span id="progress">0</span><br>
    <input type="text" id="uri" value="ws://localhost:8887"
            style="width: 200px;"> <input type="button" id="connect"
            value="Connect"><input type="button" id="disconnect"
            value="Disconnect" disabled="disabled"><!--ws://192.168.137.178:8081/websocketchat/hao/binupload?r=haha-->
    <form >
        <input id="file" type="file" multiple /> 
        <input type="button" id="sendFileForm" value="测试" />
         <input type="button" id="reset" value="清空消息框" />
    </form>
    <form>
        <textarea id="log" rows="30" cols="100"
            style="font-family: monospace; color: red;"></textarea>
    </form>
</body>
</html>


java的服务端代码如下
package testupload;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.channels.NotYetConnectedException;
import java.util.Set;
import org.java_websocket.WebSocket;
import org.java_websocket.WebSocketServer;
import org.java_websocket.handshake.ClientHandshake;
public class UploadServer extends WebSocketServer {
	public UploadServer(int port) throws UnknownHostException {
		super(new InetSocketAddress(InetAddress.getByName("192.168.137.178"), port));
	}
	public UploadServer(InetSocketAddress address) {
		super(address);
	}
	@Override
	public void onOpen(WebSocket conn, ClientHandshake handshake) {
		try {
			this.sendToAll("new");
		} catch (InterruptedException ex) {
			ex.printStackTrace();
		}
		System.out.println(conn + " entered the room!");
	}
	@Override
	public void onClose(WebSocket conn, int code, String reason, boolean remote) {
		try {
			this.sendToAll(conn + " has left the room!");
		} catch (InterruptedException ex) {
			ex.printStackTrace();
		}
		System.out.println(conn + " has left the room!");
	}
	public String fileName;
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	@Override
	public void onMessage(WebSocket conn, String message) {
		// try {
		// this.sendToAll( message );
		// } catch ( InterruptedException ex ) {
		// ex.printStackTrace();
		// }
		// System.out.println( conn + ": " + message );
		System.out.println("文件名" + message);
		// 将文件名写入连接对象中,(需要手动修改webSocket类)
		this.setFileName(message);
		try {
			conn.send("ok");
		} catch (NotYetConnectedException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	public void onMessage(WebSocket conn, byte[] message) {
		System.out.println("收到二进制流:");
		// 将二进制流保存为文件, 文件名从连接对象中取出
		saveFileFromBytes(message, "D:/c/apache-tomcat-7.0.62/webapps/websocketchat/src/" + this.getFileName());
		// 告诉前台可以继续发送了.
		try {
			conn.send("ok");
		} catch (NotYetConnectedException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	public static boolean saveFileFromBytes(byte[] b, String outputFile) {
		FileOutputStream fstream = null;
		File file = null;
		try {
			file = new File(outputFile);
			fstream = new FileOutputStream(file, true);
			fstream.write(b);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			if (fstream != null) {
				try {
					fstream.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return true;
	}
	@Override
	public void onError(WebSocket conn, Exception ex) {
		ex.printStackTrace();
	}
	public void sendToAll(String text) throws InterruptedException {
		Set<WebSocket> con = connections();
		synchronized (con) {
			for (WebSocket c : con) {
				c.send(text);
			}
		}
	}
	public static void main(String[] args) throws InterruptedException, IOException {
		WebSocket.DEBUG = true;
		int port = 8887;
		try {
			port = Integer.parseInt(args[0]);
		} catch (Exception ex) {
		}
		UploadServer s = new UploadServer(port);
		s.start();
		System.out.println("UploadServer started on port: " + s.getPort());
		// 服务端 发送消息处理部份
		BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in));
		while (true) {
			String in = sysin.readLine();
			s.sendToAll(in);
		}
	}

}

只需要一个jar
websocket.jar
http://dl.iteye.com/topics/download/decd7d91-9d2a-381f-bcea-fb0e202f6e3c

  • 大小: 13.2 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics