Blob from javascript binary string

30,215

Is the blob that you used not available for use anymore?
Do you have to use readAsBinaryString? Can you use readAsArrayBuffer instead. With an array buffer it would be much easier to recreate the blob.

If not you could build back the blob by cycling through the string and building a byte array then creating a blob from it.

$('input').change(function(){
    var frb = new FileReader();
    frb.onload = function(){
        var i, l, d, array;
        d = this.result;
        l = d.length;
        array = new Uint8Array(l);
        for (var i = 0; i < l; i++){
            array[i] = d.charCodeAt(i);
        }
        var b = new Blob([array], {type: 'application/octet-stream'});
        window.location.href = URL.createObjectURL(b);
    };
    frb.readAsBinaryString(this.files[0]);
    
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="file">

Share:
30,215
Will Hardwick-Smith
Author by

Will Hardwick-Smith

Third year software engineer and tutor at Victoria University in Wellington. Interested UX in general, mobile dev, visualisations and AI!

Updated on November 02, 2020

Comments

  • Will Hardwick-Smith
    Will Hardwick-Smith over 3 years

    I have a binary string created with FileReader.readAsBinaryString(blob).

    I want to create a Blob with the binary data represented in this binary string.

  • Will Hardwick-Smith
    Will Hardwick-Smith over 9 years
    Yes, that worked for me. I've edited your answer with code that worked for me. One difference from my original question is that in this case, binaryString came from a file using the node.js method fs.readFileSync(path, "binary").
  • Paul Weber
    Paul Weber almost 9 years
    This worked great for me! I just had to change one thing - i could not use the Uint8Array directly in the Blob constructor but had to pass new Blob([array.buffer]) instead, else the content of the Blob was just the serialized Uint8Array.