File to Byte Array in WinJS

2019-05-17 01:13发布

问题:

I'm tinkering with some Windows Store development in JavaScript and I seem to be stuck on how to get a byte array from a binary file. I've found a couple of examples online, but they all seem to only read in text whereas my file is an image. I'm opening the file like this:

Windows.Storage.FileIO.readBufferAsync(photos[currentIndex]).done(function (buffer) {

    var dataReader = Windows.Storage.Streams.DataReader.fromBuffer(buffer);
    var fileContent = dataReader.readString(buffer.length);
    dataReader.close();

    // do something with fileContent

});

Where photos[currentIndex] is a file (loaded from getFilesAsync()). The error in this case, of course, is that readString fails on binary data. It can't map the "characters" into a string. I also tried this:

Windows.Storage.FileIO.readBufferAsync(photos[currentIndex]).done(function (buffer) {

    var bytes = [];
    var dataReader = Windows.Storage.Streams.DataReader.fromBuffer(buffer);
    dataReader.readBytes(bytes);
    dataReader.close();

    // do something with bytes

});

But bytes is empty, so I think I'm using this incorrectly. I imagine I'm just overlooking something simple here, but for some reason I just can't seem to find the right way to read a binary file into a byte array. Can somebody offer a second set of eyes to help?

回答1:

Figured it out almost immediately after posting the question, but I figure I'll leave the answer here for posterity...

I needed to declare the array in the second example differently:

Windows.Storage.FileIO.readBufferAsync(photos[currentIndex]).done(function (buffer) {

    var bytes = new Uint8Array(buffer.length);
    var dataReader = Windows.Storage.Streams.DataReader.fromBuffer(buffer);
    dataReader.readBytes(bytes);
    dataReader.close();

    // do something with bytes

});

My JavaScript isn't quite up to par, so I guess I didn't understand how the array declaration was supposed to work. (When I do vanilla JavaScript in a browser, I always just declare empty arrays like I originally did and append to them.) But this does the trick.