我想通过HTTP post API上传图片。我的意见是这样的。
<input type="file" (change)="changedata($event)" name="file"/>
和Changedata()函数。
let fileList: FileList = event.target.files;
if (fileList.length > 0) {
let file: File = fileList[0];
let formData: FormData = new FormData();
formData.append('File', file, file.name);
this.mainservice.updateIcon(formData).subscribe(responseData=>{
console.log(' Reposnce Data ',responseData)
})
}
当我检查请求有效负载时,它不发送图像..请参阅https://www.screencast.com/t/vKFKj0S3
我如何在base64中发送图像?
答案 0 :(得分:0)
<input id="profile" type="file" name="profile" required (change)="uploadImage()">
和上传图像功能
public uploadImage(): void {
let files = this.element.nativeElement.querySelector('#profile').files;
let formData = new FormData();
let file = files[0];
formData.append( 'userID', this.userID); // if you want pass other value
formData.append('profile', file, file.name); // add image in FormData
// pass image to service
this.fileUpload.uploadFile(formData).subscribe( res => res);
}
在uploadFile中 - &gt;&gt;服务
public uploadFile(formdata: any ) {
return this.http.post('ApiURL here', formdata).catch(this.errorHandler);
// return this.apiUrl;
}
private errorHandler(error: Response) {
console.error('Error Occured: ' + error);
return Observable.throw(error || 'Some Error on Server Occured');
}