I have a datachannel connection between two browsers, and would like to break a file into chunks and send them to/from the clients.
I can read the file and break it up into chunks just fine. However I need a way for the receiving client to know
which file the chunk of data relates to (unique identifier).
which place the chunk applies to in reconstruction (index number).
When transferring binary data in the browser, it seems the entire payload must be binary. So I can't, for example, create a JSON object with the above properties, and have a data
property with the actual binary chunk.
I guess I need to wrap the file chunk into a secondary binary blob which contains the identifier and index. The receiving client would then decode the first, wrapper, chunk to check the meta-data, then handle the actual file chunk based on that information.
How can I do this in the browser? I have done a lot of google searching but can't seem to find any information on this, so wonder if I'm perhaps overlooking something which can help ease this process?
You have to create your own protocol for transfering files.
File
/Blob
object. You probably also use split()
method to get chunks.You can simply use a Uint8Array to transfer data.
Create a protocol that satisfies your needs, for example:
Send an initial package (e.g. type 0x01)
Send Chunks of data (e.g. type 0x02)
Note: If transfering multiple files, you should add a id or something else.
On the receiver side you can wait for the initial package and and create a new Uint8Array
with length of the total file. Afterwards you can use set()
to add received data at the chunk position (offset = 0-based-chunk-number
*chunk-size
). When all chunks are received, you can create the Blob
.