symfonyBeginner
symfonyBeginner

Reputation: 53

uploading a file via API, multipart/form-data

I'm using rembg in my app: https://github.com/danielgatis/rembg

What i want to do Upload a image to my API endpoint using http.post;

Running this code:

this.photoService.readFile(this.publicImageUrl.uri).then(res => {

let data = res;
this.oryginalImg = data.data;

this.ApiService.removeBG(this.publicImageUrl.uri).then(res => console.log(res))

})

readFile():

async readFile(path: string) {
  const contents = await Filesystem.readFile({
  path: path
});

return contents;
}

removeBG():

  async removeBG(file: any) {

  let headers = { 'content-type': 'multipart/form-data' };
  let formData = new FormData();
  formData.append('file', file);

  let body = {
    'body': formData
   }


   let promise = new Promise<void>((resolve, reject) => {
      this.http.post(environment.photoServiceURL, body, { headers }).toPromise().then(res => { console.log(res); resolve(); }).catch(err => console.log(err));
});

  }

Response is: Missing boundary in multipart.

Request:

It's look like there's something wrong with attaching a file, am I right? How to attach file from filesystem and upload this file via API?

Upvotes: 1

Views: 1050

Answers (1)

Flo
Flo

Reputation: 3117

If you using @capacitor/filesystem you need to to the follow:

const response = await fetch(file.data); // where file comes from Filesystem.readFile
const blob = await response.blob();
const formData = new FormData();
formData.append('file', blob, file.name);

// ...then upload your form as above

You need to fetch the data of your given file, get the blob and then set the FormData. Here is a example from Ionic.

Greetings, Flo

Upvotes: 1

Related Questions