0

我想通過HTTP post API上傳圖片。我的意見是這樣的。Angular 4圖片上傳

<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
<input id="profile" type="file" name="profile" required (change)="uploadImage()"> 

和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

- >>服務

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