5

How can I convert a uploaded file to byte array in Angular/Typescript?

Component.ts

 buildRequest(): CreateRequest { 
 var reader = new FileReader();  
    return {
      create: {
        fileData: this.reader.readAsArrayBuffer(this.fileToUpload)        
      }
    };
  }

Model

export interface CreateRequest {
    create: {
      fileData: Uint8Array[]; // Also, is this correct representation of byte array?
    };
  }

Currently, I am getting an error when I am assigning ReadAsArrayBuffer function to fileData -

"Type 'void' is not assignable to type 'Uint8Array[]'"

.

What is the correct way of sending byte array to API request?

Mikhail Zhuikov
  • 1,213
  • 2
  • 9
  • 19
Learn AspNet
  • 1,192
  • 3
  • 34
  • 74
  • 1
    Not in a position to check, but it seems readAsArrayBuffer might not return anything, or it might be a promise or something. I would first inspect the return signature of readAsArrayBuffer.. – MikeOne Sep 24 '19 at 17:35

1 Answers1

-2

The question has been answered here!

I believe the attribute is string, blob or any.

export interface CreateRequest {
    create: {
      fileData: string|any;
    };
}

Btw, IO functions are asynchronous (probably in any language)!, you need use event listeners.

reader.addEventListener('loadstart', handleEvent);
reader.addEventListener('load', handleEvent);
reader.addEventListener('loadend', handleEvent);
reader.addEventListener('progress', handleEvent);
reader.addEventListener('error', handleEvent);
reader.addEventListener('abort', handleEvent);

https://developer.mozilla.org/en-US/docs/Web/API/FileReader/load_event

If you need another references, hope your helps!

https://nehalist.io/uploading-files-in-angular2/

Rafael Pizao
  • 742
  • 8
  • 21