12

I have a typed array full of binary data that is being generated from an ArrayBuffer

var myArr = new Uint8Array(myBuffer);

I am presenting this to the user with

var blob = new Blob(myArr, {type: "octet/stream"};
var blobURL = URL.createObjectURL(blob);

and inserting a link that is

"<a href=" + blobUrl + " download=" + filename "/a>"

Later, I am letting the user select the file from disk, and using a file reader to do with

var reader = new FileReader();

reader.onload = function () {
console.log(reader.result);
};

reader.readAsArrayBuffer(sourceFile);

The problem is, it seems like no matter what I do, I get a "string" of the file's contents. In fact, when I save the file, I can open it, and it is plainly human readable. I.E. if my Uint8Array was {"0" : "51", "1" : "52", "2" : "53" }

I can open the downloaded blob in a text editor and I just see "515253" which I don't think is what should be happening.

How can I make a link to a file download for my file that is formatted properly so I can read it back in an dget the right values?

Derek
  • 11,715
  • 32
  • 127
  • 228

3 Answers3

17

As it turns out, the problem was that I had a syntax error in the creation of the Blob.

The corrected code looked like: var blob = new Blob([myArr], {type: "octet/stream"});

I'm not really sure why if I am already passing an ArrayBuffer argument. Why I need bracket notation? Seems redundant?

Julio C.
  • 55
  • 5
Derek
  • 11,715
  • 32
  • 127
  • 228
  • 1
    The first argument is always an array which in theory can hold multiple parts (f.ex. multiple ArrayBuffer views) which are then concatenated internally (very useful when building things like binary file formats). –  Jun 21 '16 at 22:26
6

According to Mozilla

https://developer.mozilla.org/en-US/docs/Web/API/Blob#Example_for_creating_a_URL_to_a_typed_array_using_a_blob

var blob = new Blob([typedArray.buffer], {type: 'application/octet-stream'});
NiKO
  • 2,610
  • 1
  • 19
  • 19
1
const download = function (data) 
{
    const blob = new Blob(data, { type: "octet/stream"});
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.setAttribute('href', url)
    a.setAttribute('download', app.lastSub+"_"+new Date().toISOString()+'.py');
    a.click()
}

const get = async function () {
    download(app.psspyList);
}