首页 > 解决方案 > 如何将 formData、图像传递给我正在使用的 API 的 HTTP 发布请求?

问题描述

我不知道如何将我的文件/图像传递给formData. 谁能告诉我如何以正确的方式做到这一点?

myImage = '../assets/imgs/testing.jpg';

recognize(){

    let headers = new Headers();

    headers.append('Content-Type', 'application/json');
    headers.append('apikey', 'myAPI');

    console.log(headers);



    let formData = {
       file: {

      }
    }

    console.log(formData);

    this.http.post('https://api.taggun.io/api/receipt/v1/simple/file', formData, {headers: headers})
      .map(res => res.json()).subscribe(data =>{
        console.log(data);
      });
    }
  }

标签: angularapiionic3

解决方案


如果您使用的是角度(如标签中指定),则解决方案如下:

组件 HTML 模板:

<input
style="display: none"
type="file" (change)="onImgChanged($event)"
#fileInput>
<button (click)="fileInput.click()">Select Your Image</button>
<button (click)="onUpload()">Upload!</button>

零件:

// variable for holding your image
selectedImg;

onImgChanged(event) {
  this.selectedImg = event.target.files[0];
}

onUpload() {
  const headers = new Headers({
    'Accept': 'application/json',
    'apikey', 'myAPI'
  });

  console.log(headers);

  // get instance of formData:
  const formData = new FormData();

  // append an image to your formData:
  formData.append('myFile', this.selectedImg, this.selectedImg.name);

  // make post request:
  this.http.post('https://api.taggun.io/api/receipt/v1/simple/file', formData, {headers: headers})
    .map(res => res.json())
    .subscribe(data => {
      // response from api...
      console.log(data);
    });
}

推荐阅读