Angular4 - FormData对象为空

时间:2018-04-20 12:18:47

标签: javascript angular multipartform-data

尝试使用文件

发送FormData
<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);
       }
   }

表单数据为空。 FormData {}

2 个答案:

答案 0 :(得分:0)

您可以尝试

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

答案 1 :(得分:0)

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