Adding JavaScript for transferring files via WebSockets
We will discuss the RTCDataChannel-based file sharing, but first let's look at how we can implement this using WebSockets. The file_input()
function described previously calls the following send_file()
function.
// send selected file function send_file(name, file_id, data) { ... var img = document.getElementById("file_img_src"); img.onload = function() { ... send_file_parts("file", file_id, data); } img.src = data; }
First, we select the file_img_src
element that we will use for loading the file data. Then, we set up an onload
handler, and at the end of this, we call send_file_parts()
. This will slice the file data into chunks and send each of them to the other server once the image has fully loaded. Then, we start the whole process by assigning the data to image.src
.
Now, let's look at the send_file_parts()
function:
// break file into parts and send each of them separately function send_file_parts(type, id, data) { ...