angular - 如何将 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);
});
}
}
解决方案
如果您使用的是角度(如标签中指定),则解决方案如下:
组件 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);
});
}
推荐阅读
- c++ - 多线程堆栈,向量下标超出范围
- sas - 如何在这个 SQL 过程中以 date9 的格式显示日期?
- javascript - 如何让对象将自身添加到数组中
- android - 单一活动应用程序和视图模型的最佳实践
- python - 删除具有列条件的整行
- filter - 带有连字符和复合词的 Solr Tokenizer(德语)
- python - 如何将图像或字节数组从图像以 JSON 格式从客户端发送到后端服务器,然后将其存储在 Mongodb
- database - Laravel 5.8 make:auth 更改字段名称不起作用
- html - 淘汰赛 - Foreach 绑定 - 如何在 HTML 中反映更新的值
- parsing - attoparsec 中 Zepto 解析器的示例或教程