问题
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?
回答1:
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?
回答2:
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'});
来源:https://stackoverflow.com/questions/36985406/javascript-save-typed-array-as-blob-and-read-back-in-as-binary-data