2

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.

Giannis
  • 1,790
  • 1
  • 11
  • 29

1 Answers1

7

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");
     }
}
Sid
  • 451
  • 3
  • 9
  • now it becomes a Promise . how can I make promise of Promise to Uint8Array? (can you update your code to show me that please?) –  Apr 06 '21 at 12:40
  • I think you're doing something like this `console.log(file.arrayBuffer().then(buff => new Uint8Array(buff)));` then you will have the promise output. But you should do the operations inside the promise then callback. Just take a look how promise works in JS https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise. – Sid Apr 06 '21 at 13:03
  • ok i will look for it –  Apr 06 '21 at 13:34
  • also updated the answer that may help better. – Sid Apr 06 '21 at 13:35