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?

1
  • 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.. Commented Sep 24, 2019 at 17:35

1 Answer 1

-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/

Sign up to request clarification or add additional context in comments.

4 Comments

Can you change my code and try to get it working. I tried this but this isn't working
Friend! Method readAsArrayBuffer is Javascript. You tried this?
This returns void. How do I send it over to the API?
IO functions are asynchronous (probably in any language)! Another example... developer.mozilla.org/en-US/docs/Web/API/FileReader/load_event

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.