Sven Lorenz
Sven Lorenz

Reputation: 71

How to get 2 files from 2 different HTML inputs in FileReader in Angular 8?

In my current project 2 JSON files have to be put together. In order to be able to use all files, they can be integrated via 2 HTML inputs. I used the JS FileReader to edit the two files.

Is there a way to make both files available at the same time?

HTML:

<input (change)="onFileChange($event)" [(ngModel)]="json1" type="file">
<input (change)="onFileChange($event)" [(ngModel)]="json2" type="file">

Component:

public onFileChange(event) {
    var one = this.json1;
    var two = this.json2;
    one = event.target.files;
    two = event.target.files;
    if (one) {
      var i = 0, f; f = one[i]; i++;
      console.log(i);
    } else {
      var i = 0, f2; f2 = two[i]; i++;
      console.log(i);
    }
    var fileReader = new FileReader();
    fileReader.onload = function(fileLoadedEvent) {
        var showJSON = fileLoadedEvent.target.result;
    };
    fileReader.readAsText(f, "UTF-8");
    console.log(f);
  };

My current idea is to give each file a number which you can then work with, only so far this has not worked.

Upvotes: 1

Views: 156

Answers (1)

Sameer
Sameer

Reputation: 5188

Add multiple attribute to input element

<input type="file" multiple (change)="onFileChange(myInput)" #myInput>

and access using

onFileChange(myInput) {
  console.log(myInput.files) //You will get array of files here loop through each 
}

Upvotes: 1

Related Questions