Search code examples
htmlfiletransferfileapi

How to send a single file from one client browser to another without saving it on server (node.js) using html5 and File API


I need to send file from one client browser to another without having to save it on server (node.js) How am I able to do it with HTML5 and File API?

Actually the solution implemented:

Final solutionlooks like this:

  1. On seeding client get file from input[type=file]

  2. File array contains a key storing file Object. Use slice/mozSlice method to split it chunks so that Object.slice will return Blob object.

  3. Using FileReader Blob can be read into raw binary data or base64 encoded data. FileReader implements readAsDataURL(blob) for reading to base64 and readAsBinaryString(blob) for reading to raw binary data. See 'onloadend' FileReader event to get access to data read from blob.

  4. You should implement logic to calculate chunks number according to chunk size (usually 1024 * 64) and next slice start/stop position to get chunks of exactly same size

  5. Encoded data is sent via socket.io to node.js where the only server-side logic is to send received data to pear also connected through socket.io

  6. Guess most interesting is to get all those chunks together into blob on pear's client browser. Creating Blob from raw binary data will cause the wrong size of blob and in result to wrong file size. That's why we are transfering base64 encoded data from seeder.
    Decoding might become the problem as we must implement it by ourselves.

    function decode64 (data) {
        var mimeString = data.split(',')[0].split(':')[1].split(';')[0],
        // remove all chars before ','
        byteString = atob(data.split(',')[1]),
        // if BlobBuilder available
        ab = new ArrayBuffer(byteString.length),
        ia = new Uint8Array(ab);
    
        for (var i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }
        blob    = new Blob([ia], {'type' : (mimeString) });
    return blob;
    }
    

Having decoded data to blob we must push it to array containing aother decoded chunks. 7. Create a Blob from array of chunks decoded to blobs, smth like this

new Blob (array_of_decoded_blobs_returned_by_decode64_function, {type:'mime-type'})

Using file api write blob to file or do whatever you want to do


Solution

  • Websockets are the only way I can imagine doing this, and you'd still need a server-side proxy.

    See: Do websockets allow for p2p (browser to browser) communication?