简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM