【问题标题】:Angular 4 Image UploadAngular 4 图片上传
【发布时间】:2017-09-20 08:48:45
【问题描述】:

我想通过 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 中发送图像?

【问题讨论】:

    标签: angular image-uploading angular4-forms angular4-httpclient


    【解决方案1】:
    <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 ->>Service

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-11
      • 2018-10-04
      • 2019-04-15
      • 2017-11-15
      • 2016-05-19
      • 2022-01-15
      相关资源
      最近更新 更多