8

I can convert a blob to string using FileReader, but I want to convert it back:

var reader = new window.FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
   base64data = reader.result;
   var blobToSend = base64data.substr(base64data.indexOf(',')+1);
   rtcMultiConnection.send({"command":{
       "recording":blobToSend,
       "type":blob.type,
       "size":blob.size
   }});
}

This is sent with https://github.com/muaz-khan/RTCMultiConnection but the main question is how to reconstruct the blob after being sent. Sadly sending the blob as is didn't work.

1
  • 1
    Chrome supports array-buffer, and RTCMultiConection support it as well. Blob-support in chrome is work-in-progress. So for now, you can use "fileReader.readAsArrayBuffer". For your information, this will work: connection.send(recorder.blob) RTCMultiConnection will auto share the entire blob (of any size). Remote users will receive the complete blob in "onFileEnd" event. Commented Mar 30, 2016 at 7:17

1 Answer 1

4

source: Creating a Blob from a base64 string in JavaScript This method correctly converts back base64 data to the original binary data. For the sake of performance improvements, the data is processed in blocks of the size of sliceSize. NOTE: source is in TypeScript

    public static Base64ToBlob(b64Data, contentType = "", sliceSize = 512): Blob
    {
        const byteCharacters = atob(b64Data);
        const byteArrays = [];

        for (let offset = 0; offset < byteCharacters.length; offset += sliceSize)
        {
            const slice = byteCharacters.slice(offset, offset + sliceSize);
            const byteNumbers = new Array(slice.length);

            for (let i = 0; i < slice.length; i++)
            {
                byteNumbers[i] = slice.charCodeAt(i);
            }

            const byteArray = new Uint8Array(byteNumbers);
            byteArrays.push(byteArray);
        }

        const blob = new Blob(byteArrays, { type: contentType });
        return blob;
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.