简体   繁体   中英

Angular4 - FormData object is empty

Trying to send FormData with file

<input type="file"(change)="showPreviewImage($event)">

showPreviewImage(event: any) {
    if (event.target.files && event.target.files[0]) {

        let fileList: FileList = event.target.files; 
        let file: File = fileList[0];
        const formData:FormData = new FormData();
        formData.append('photoUrl', file, file.name);
        formData.append('TEST','ujsgfsdf');
        console.log(formData);
       }
   }

Form data is empty. FormData { }

You can try

formData.forEach((value, key) => {                                                                                                                             
   console.log("key (%s): value (%s)", key, value);                                                                                                           
})

HTML

 <div>
  <input #fileUpload type="file" (click)="fileUpload.value = null" (change)="importFile($event)" style="display:none;" name="userimage">
  <img [src]="url">
 <div>
 <button mat-raised-button color="accent" (click)="fileUpload.click()">CHOOSE IMAGE</button>

TS

uploadFiles: File;
url = '';

importFile(event : any) {
  if(event.target.files && event.target.files[0]) { 
    var reader = new FileReader();
    reader.onload = (event:any) => {
      this.url = event.target.result;
    }
    reader.readAsDataURL(event.target.files[0]);
    this.uploadFiles = event.target.files[0];
  }
}

//now where you submit form in this function do this

 saveDetails(){
   if(this.uploadFiles != null){
      const formData = new FormData();
      formData.append('uploadFiles', this.uploadFiles, this.uploadFiles.name);
   }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM