Skip to content

Instantly share code, notes, and snippets.

@wolfmanjm
Created January 21, 2019 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wolfmanjm/1e4c55dd833065ab7609d410c72247b5 to your computer and use it in GitHub Desktop.
Save wolfmanjm/1e4c55dd833065ab7609d410c72247b5 to your computer and use it in GitHub Desktop.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload Files</title>
</head>
<body>
<h2>File Upload</h2>
Select file
<input type="file" id="filename" />
<br>
<input type="button" value="Connect" onclick="connectChatServer()" />
<br>
<input type="button" value="Upload" onclick="sendFile()" />
<script>
var ws;
function connectChatServer() {
ws = new WebSocket("ws://192.168.1.101/upload");
ws.binaryType = "arraybuffer";
ws.onopen = function() {
alert("Connected.")
};
ws.onmessage = function(evt) {
alert(evt.msg);
};
ws.onclose = function() {
alert("Connection is closed...");
};
ws.onerror = function(e) {
alert(e.msg);
}
}
function sendFile() {
var file = document.getElementById('filename').files[0];
var reader = new FileReader();
var rawData = new ArrayBuffer();
reader.loadend = function() { }
reader.onload = function(e) {
rawData = e.target.result;
ws.send(file.name);
ws.send(rawData.byteLength);
for (var i = 0; i < rawData.byteLength; i+=1024) {
if(i+1024 <= rawData.byteLength) {
console.log("sending: " + i + " - " + (i + 1024));
ws.send(rawData.slice(i, i+1024));
}else{
console.log("sending: " + i + " - " + (rawData.byteLength - i));
ws.send(rawData.slice(i));
}
}
alert("the File has been transferred.")
}
reader.readAsArrayBuffer(file);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment