将input = file转换为byte数组 [英] Convert input=file to byte array

查看:181
本文介绍了将input = file转换为byte数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将通过输入文件获得的文件转换为byte []。
我尝试使用FileReader,但我必须错过一些东西:

I try to convert a file that i get through an input file into a byte[]. I tried with a FileReader, but i must miss something :

var bytes = [];
var reader = new FileReader();
reader.onload = function () {
   bytes = reader.result;
};
reader.readAsArrayBuffer(myFile);

但最后,我的字节var不满足字节数组。

But in the end, my bytes var doesn't content a byte array.

我看过这篇文章:获取字节数组通过输入类型=文件但它不以字节[]结束,并且不推荐使用readAsBinaryString()

I saw this post : Getting byte array through input type = file but it doesn't ends with a byte[], and readAsBinaryString() is deprecated

我错过了什么?

推荐答案

面对类似的问题,其真正的'reader.result'不会以'byte []'结尾。所以我把它投射到Uint8Array对象。这也不是一个完美的'byte []',所以我不得不从它创建一个'byte []'。这是我对这个问题的解决方案,对我来说效果很好。

Faced a similar problem and its true the 'reader.result' doesn't end up as 'byte[]'. So I have cast it to Uint8Array object. This too is not a perfect 'byte[]' ,so I had to create a 'byte[]' from it. Here is my solution to this problem and it worked well for me.

var reader = new FileReader();
var fileByteArray = [];
reader.readAsArrayBuffer(myFile);
reader.onloadend = function (evt) {
    if (evt.target.readyState == FileReader.DONE) {
       var arrayBuffer = evt.target.result,
           array = new Uint8Array(arrayBuffer);
       for (var i = 0; i < array.length; i++) {
           fileByteArray.push(array[i]);
        }
    }
}

'fileByteArray'就是你的意思正在找。看到评论,似乎你做了同样的,仍然想分享方法。

'fileByteArray' is what you are looking for. Saw the comments and seems you did the same, still wanted to share the approach.

这篇关于将input = file转换为byte数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆