[Fixed] convert file to uInt8Array in angular

Issue

I want to upload files from angular to postgresql using golang api.

In the angular part, I want to convert my file to uInt8Array. I have converted the array, but it is inside something I don’t know of (as shown in the image)

screenshot-1

So how can I get the uInt8Array inside a variable like let x : uInt8Array = y;

Here is how far I tried.

x.component.html

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

x.component.ts

onFileSelected(event) {
 console.log("called");
 const file: File = event.target.files[0];
 if (file) {
   console.log(file.arrayBuffer());
   console.log("call finished");
 }
}

Output was in previous screenshot.

Solution

Just construct a Uint8Array from array buffer output

file.arrayBuffer().then(buff => {
    let x = new Uint8Array(buff); // x is your uInt8Array
    // perform all required operations with x here.
});

As per question it should be looking like this

onFileSelected(event) {
     console.log("called");
     const file: File = event.target.files[0];
     if (file) {
         file.arrayBuffer().then(buff => {
             let x = new Uint8Array(buff); // x is your uInt8Array
             // perform all required operations with x here.
             console.log(x);
         });
         console.log("call finished");
     }
}

Leave a Reply

(*) Required, Your email will not be published