Property 'arrayBuffer' does not exist on type 'File'

Viewed 3305

I am getting a type error while implementing code for file upload in Angular application. I am using angular 8 and typescript 3.5.3. Following is my code

Template <input type="file" id="file" (change)="handleFileInput($event.target.files)">

And function in component class

  handleFileInput(files: FileList): void {
    files[0].arrayBuffer().then((value) => {
      console.log(value);
    });
   }

While compiling I get this error: error TS2339: Property 'arrayBuffer' does not exist on type 'File'.

Any idea how to get rid of this error?

2 Answers

This error appears, because The arrayBuffer(), stream(), and text() are actually missing from the type definition of File / Blob. This is not an overlook though, according to the MDN these methods are still only part of a Working Draft and not well supported. If you want to patch the typing, to be still able to use the features like arrayBuffer() without typescript complaining, then you can extend the File interface with a missing property, i.e.:

File {
    arrayBuffer: () => Promise<ArrayBuffer>
}

For reference see: https://github.com/microsoft/TypeScript/issues/34652

Change your code html to

<input type="file" id="file" (change)="handleFileInput($event)">

Your TS

handleFileInput(event: Event) {
   const file = (event.target as HTMLInputElement).files[0];
   const reader = new FileReader();
   let preview;
   reader.onload = () => {
     this.preview = reader.result as string;
   };
   reader.readAsDataURL(file);
}
Related