0

I am trying to extract the byteArray for the file which is being selected from my Angular app. I am using "readAsArrayBuffer" property of FileReader Class to get the file as an Array Buffer, the output for which is below:

enter image description here

Below is the Code Sample for the above output:

onFileSelected(event) 
{


if (event.target.files && event.target.files.length > 0)

{
  let reader = new FileReader();
  if(event.target.files && event.target.files.length > 0) {
    let file = event.target.files[0];
    reader.readAsArrayBuffer(file);
    reader.onload = () => {

    this.form.get('file').setValue({
        filename: file.name,
        filetype: file.type,
        value:reader.result

      })
    };
  }

}

else
{
  console.log("Error");
  }
}

I am trying to get the Uint8Array from the below statement :

value:String.fromCharCode.apply(null, new Uint8Array(reader.result))

Below is the code for the same. Its the same as above with a minor change in the "value" attribute.

  onFileSelected(event) 
{


if (event.target.files && event.target.files.length > 0)

{
  let reader = new FileReader();
  if(event.target.files && event.target.files.length > 0) {
    let file = event.target.files[0];
    console.log(file);
    reader.readAsArrayBuffer(file);
    reader.onload = () => {

    this.form.get('file').setValue({
        filename: file.name,
        filetype: file.type,
        value:String.fromCharCode.apply(null, new Uint8Array(reader.result))

      })
    };
  }

}

else
{
  console.log("Error");
  }
}

The output for which is below. Its an Error:

enter image description here

i tried the implementing the resolution given at the below thread but was unsuccessful in doing so:

Maximum call stack size exceeded error

I need my file as a byte array so that i can pass it to a REST API which only accepts the file as a byteArray. Thanks !

nemish nigam
  • 65
  • 2
  • 10
  • functions have a maximum number of arguments they can accept and you've got through it with your 3696498 arguments. But what are you trying to do exactly here? If you want to extract text from this File, use readAsText. If you want a string version of the binary data in this File, you're doing it wrong anyway with String.fromCharCode. Us3 readAsDataURL instead. – Kaiido Jul 18 '18 at 14:10
  • Ah I missed the last paragraph... If you send the File directly, the server will receive it as a "byteArray". – Kaiido Jul 18 '18 at 14:20
  • what shall I put the statement then as to pass it directly as a file ? – nemish nigam Jul 18 '18 at 14:49
  • If you are sending your request from an html `
    ` then just append your input in this form and be sure it has a name. If it's by ajax, then you can either xhr.send(file) directly or use a FormData
    – Kaiido Jul 18 '18 at 22:29
  • FormData worked for me. Thanks Kaiido ! – nemish nigam Jul 19 '18 at 05:07

0 Answers0