我不知道如何将文件/图像传递到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);
});
}
}
答案 0 :(得分:0)
如果使用的是角形(如标记中所指定),则解决方法如下:
组件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);
});
}