Convert input=file to byte array

落花浮王杯 提交于 2019-11-28 02:03:50

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' is what you are looking for. Saw the comments and seems you did the same, still wanted to share the approach.

Seems to me you just want to get files into an array? How about these functions - one where you can read it as text, another as a base64 byte string, and if you really want the readAsArrayBuffer array buffer output, I've included that, too:

document.getElementById("myBtn").addEventListener("click", function() {
  uploadFile3();
}); 

var fileByteArray = [];

function uploadFile1(){
  var files = myInput.files[0];
  var reader = new FileReader();
  reader.onload = processFile(files);
  reader.readAsText(files); 
}

function uploadFile2(){
  var files = document.querySelector('input').files[0];
  var reader = new FileReader();
  reader.onload = processFile(files);
  reader.readAsDataURL(files); 
}

function uploadFile3(){
  var files = myInput.files[0];
  var reader = new FileReader();
  reader.onload = processFile(files);
  reader.readAsArrayBuffer(files); 
}

function processFile(theFile){
  return function(e) { 
    var theBytes = e.target.result; //.split('base64,')[1]; // use with uploadFile2
    fileByteArray.push(theBytes);
    document.getElementById('file').innerText = '';
    for (var i=0; i<fileByteArray.length; i++) {
        document.getElementById('file').innerText += fileByteArray[i];
    }
  }
}
<input id="myInput" type="file">    
<button id="myBtn">Try it</button>
<span id="file"></span>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!