0

I want to have an input field with file. Put the file into an Angular object, then upload it into API.

But, when I log file, it's always empty (like {}). The rest API receive empty object too. Server-side result: {"id":0,"name":"test","image":{}}.

My object:

export interface Image {
    id: number;
    name: string;
    image: Blob;
}

In my components, the HTML is <input type="file" name="file" id="file" (change)="handleFileInput($event.target)" required>, and my typescript code is:

public imageEdit: Image = { id: 0, name: "something" };

public handleFileInput(file: any): void {
  let files = file.files as FileList;
  if(files.length == 1) {
    console.log(JSON.stringify(files));
    this.imageEdit.image = files.item(0); // also tried with "files[0]"
    this.http.post("my/url", this.imageEdit); // here send to server
  }
}

I also tried to use Uint8Array instead of Blob.

Elikill58
  • 4,050
  • 24
  • 23
  • 45
  • https://stackblitz.com/edit/angular-file-upload?file=app%2Fapp.component.ts – Vikas Dec 15 '22 at 11:19
  • @Vikas this send formdata, not a custom object. That's my issue, I don't know how to do without using FormData – Elikill58 Dec 15 '22 at 11:21
  • @Elikill58 - Not sure I understand the problem with using FormData, but here's an answer to a similar question: https://stackoverflow.com/a/28212708/589227 – Sean Chase Dec 15 '22 at 14:49
  • @SeanChase this doesn't solve the empty content and there is the same issue as FormData, it's not a custom object – Elikill58 Dec 15 '22 at 16:04

1 Answers1

0

It doesn't really answer, but I change something and now it works. Now, I'm using the full body of POST request to send it.

On server, I'm using context.bodyInputStream() to get the content as stream (and put it in database as blob).

On client, with angular, I'm using http.post("my/url", event.target.files[0]).

Elikill58
  • 4,050
  • 24
  • 23
  • 45