Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript convert blob to string and back

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.

like image 546
msj121 Avatar asked Mar 30 '16 06:03

msj121


People also ask

Can we convert blob to string?

Blob blob = rs. getBlob(cloumnName[i]); byte[] bdata = blob. getBytes(1, (int) blob. length()); String s = new String(bdata);

How do I get text from blob?

To get the string from a blob with JavaScript, we can use the Response object's text method. const text = await new Response(blob). text();

How do I convert blob data to readable format?

If you want to update the BLOB datatype column to the TEXT datatype column. Follow these steps: Alter the table and add a column having data type TEXT. Add content to that column after converting BLOB data to TEXT date.

Is blob a data type in JavaScript?

The Blob object represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a ReadableStream so its methods can be used for processing the data. Blobs can represent data that isn't necessarily in a JavaScript-native format.


1 Answers

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;
    }
like image 115
Majix Avatar answered Sep 19 '22 08:09

Majix