WinJS中的文件到字节数组 [英] File to Byte Array in WinJS
问题描述
我正在用JavaScript改进Windows商店的开发,而且我似乎对如何从二进制文件中获取字节数组一无所知.我在网上找到了几个示例,但是它们似乎都只能阅读文本,而我的文件是图像.我正在这样打开文件:
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
});
其中photos[currentIndex]
是文件(从getFilesAsync()
加载).当然,这种情况下的错误是readString
在二进制数据上失败.它不能将字符"映射为字符串.我也尝试过这个:
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
});
但是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?
推荐答案
在发布问题后几乎立即想出了答案,但我认为我将在此处保留答案以供后代之用...
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
});
我的JavaScript不够完善,所以我想我不明白数组声明应该如何工作. (当我在浏览器中使用普通JavaScript时,我总是只像最初那样声明空数组并追加到它们.)但这确实可以解决问题.
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.
这篇关于WinJS中的文件到字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!