繁体   English   中英

通过 API, multipart/form-data 上传文件

[英]uploading a file via API, multipart/form-data

我在我的应用程序中使用 rembg: https://github.com/danielgatis/rembg

我想做什么使用 http.post 将图像上传到我的 API 端点;

运行这段代码:

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))

})

读取文件():

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

return contents;
}

删除背景():

  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));
});

  }

响应是:多部分中缺少边界。

要求:

附加文件似乎有问题,对吗? 如何从文件系统附加文件并通过 API 上传此文件?

如果您使用@capacitor/filesystem,您需要执行以下操作:

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

您需要获取给定文件的数据,获取 blob,然后设置 FormData。 是 Ionic 的示例。

问候,弗洛

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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