IamGrooot
IamGrooot

Reputation: 1040

How to limit the file upload while uploading folder

I am allowing the user to upload the folder as below

<input type="file" (change)="onFileChanged($event)" webkitdirectory directory multiple/>

It Works as expected. But I want to limit the total size to be less than 20 MB. How Can I achieve that

  onFileChanged(event): void {
    const allFiles = event.target.files;
    console.log(allFiles);
  }

Is there any direct way to do that or I need to loop through each file and calculate the total size and check if its exceeding?

Upvotes: 1

Views: 272

Answers (3)

StepUp
StepUp

Reputation: 38154

You can get overall size of the files and prevent uploading:

onFileChanged(event): void {
    const overallSize = event.target.files
       .reduce((a, c) => {return (c.size / 1024 / 1024) + a }, 0);
    if (overallSize > 1) // 1 Mb
        alert('File size exceeds 1 MB');
    else {
    }    
}

Upvotes: 0

brk
brk

Reputation: 50326

event.target.files will return FileList. Then you can use Array.from and use reduce to get the size of each file. This is in javascript and html. Same can be done in angular

function fileUpload(e) {
  const sz = Array.from(e.target.files).reduce((acc, curr) => {
    return acc += curr.size;
  }, 0)
  console.log(sz)
}
<input type="file" multiple onchange='fileUpload(event)'>

Upvotes: 0

Kaiido
Kaiido

Reputation: 136986

Yes from a file input you need to loop through all its .files entries:

inp.onchange = e => {
  const total_size = [...inp.files].reduce( (sum, file) => (sum + file.size), 0 );
  console.log( "total size", total_size.toLocaleString( "en-US" ), "b" );
};
<input type="file" id="inp" webkitdirectory>

Upvotes: 1

Related Questions