angular4多个文件上传第二个设置文件已清除

时间:2018-06-14 05:21:36

标签: angular

我是角色

的新手

我正在使用多个文件上传

      <input #fileInput type="file"  multiple="true" ngModel class="form-control" name="image[]" accept="image/png, image/jpeg, image/gif" id="image" 
  (click)="fileInput.value = null;" (change)="onChange($event)">

要显示我在下面的代码

中使用的图像预览
<div *ngFor="let item of filelist; let i = index; " >
            <img  *ngIf="item != '' " id='img-upload' [src]="item"> 
 </div>

Image onchhange evnet

我宣布tmp_files :File[] = [] ;就像这样

   onChange(event:any) {   


  //this.fupload = event.srcElement.files;  // not working in firefox
  this.fupload = event.target.files; 
// to get the files in array

  this.tmp_files.push(event.target.files);

  //console.log(event.target.files.length+' <> '+this.dind.length);
  this.urlval = event.target.files[0].name;




  for(let i=0; i< event.target.files.length; i++ ) {

    if (event.target.files && event.target.files[i]) {
      var reader = new FileReader();
      reader.onload = (event:any) => {
        this.url = event.target.result;
        this.filelist.push(this.url);

      }
      reader.readAsDataURL(event.target.files[i]);
    }
  }        

}

我选择3个文件

Image display like this Console log for this.tmp_files variable

我再次选择2个文件

enter image description here

控制台日志为:

enter image description here

此处在tmp_files变量中,Fileset 0被清除,并且在数组中,最后选择的两个文件仅可用。

我不知道这就是原因。 (文件集0 - 长度为0.文件集1长度为2)。但在预览中我有5个fiels。请帮帮我

1 个答案:

答案 0 :(得分:0)

1)您第二次只获得2个文件的原因是文件控件在您再次进行选择时重置其集合。如果您想要多个文件,则需要一次性选择它们。否则将文件添加到本地集合中并再次添加(您现在正确地执行此操作)

2)您在预览中看到5个文件的原因是,每次选择文件时,您都会在本地集合“this.filelist”中添加它们的详细信息。此文件选择中保留此集合(需要手动重置)。

您正在正常工作,只需获取本地集合中添加的文件并使用它进行处理。代码中的任何地方都没有问题(到现在为止)

相关问题