0

At the moment my script can only handle one file being added:

fileEvent(fileInput: Event){
    this.fileName = (<HTMLInputElement>fileInput.target).files[0].name;
    this.fileSize = Math.round(((<HTMLInputElement>fileInput.target).files[0].size) / 1000);
    this.fileAdded = true;
}

This is the HTML:

<input (change)="fileEvent($event)" type="file" name="files" accept=".pcap" style='display: none;' #file>
<div id="filelist" *ngIf="fileAdded">
    <p id="file">{{ fileName }}</p>
    <p id="filesize">{{ fileSize }} KB</p>
</div>

I'm wondering how I can get the number of files inside the Input Element. I'm trying to loop through the elements to get their names and sizes so I can display them on my website.

EDIT: Apparently I haven't tried the most obvious thing, which is adding .length at the end. That solves it.

this.numOfFiles = (<HTMLInputElement>fileInput.target).files.length;
  • can you add a bit more code with explanation what you want? – Pardeep Jain Nov 07 '19 at 14:23
  • @PardeepJain I hope that's enough –  Nov 07 '19 at 14:27
  • @DariusNein You are only taking one file at a time in your input. Then how can you get multiple? – MonkeyScript Nov 07 '19 at 14:28
  • Does this answer your question? [Javascript get number of files and their filenames from file input element with multiple attribute?](https://stackoverflow.com/questions/6171013/javascript-get-number-of-files-and-their-filenames-from-file-input-element-with) – Heretic Monkey Nov 07 '19 at 14:58

3 Answers3

0

You need to use multiple attribute for input type file like this -

<input multiple (change)="fileEvent($event)" type="file" name="files" accept=".pcap" #file>

It will return you a array of files, you will get that using -

fileInput.target.files

For more in detail please refer

Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
0

Just call your fileInput.target.files.length. It's already an array of files.

fileEvent(fileInput: Event){
    this.fileName = (<HTMLInputElement>fileInput.target).files[0].name;
    this.fileSize = Math.round(((<HTMLInputElement>fileInput.target).files[0].size) / 1000);
    this.fileAdded = true;
}

You just need this line.

const numberOfFiles = fileInput.target.files.length;
Damian C
  • 2,111
  • 2
  • 15
  • 17
0

Modify your input so that it can take multiple files at a time using the multiple attribute.

<input (change)="fileEvent($event)" type="file" name="files" accept=".pcap" style='display: none;' #file multiple>

In your script, just get the length of the files.

fileEvent(fileInput: Event){
    console.log(fileInput.target.files.length)
}
MonkeyScript
  • 4,776
  • 1
  • 11
  • 28