Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a FileList object chosen by directory choser in Javascript/typescript? [closed]

I am trying to filter or remove some file from FileList object. I have gotten a FileList object form directory chooser.

<input type="file" accept="image/*" webkitdirectory directory multiple>

In my .ts file:

public fileChangeListener($event: any) {
 let selectedFiles=$event.target.files; //Object of Filelist
}

selectedFileList contain different types of file like image/jpg, image/png, application/javascript, application/pdf etc. I want to get a FileList Object with only image type file.How can I get it?

note: accept="image/*" in HTML input element do not work here.

{
lastModified:1521624250148,
lastModifiedDate:Wed Mar 21 2018 15:24:10 GMT+0600 (+06) {},
name:"rxlnn70l.bmp",
size:814138,
type:"image/bmp",
webkitRelativePath:"second/rxlnn70l.bmp",
}

Here in my code error: files.slice is not a function

like image 266
Shamim Hossain Avatar asked Feb 04 '23 00:02

Shamim Hossain


1 Answers

Use spread operator ... to convert FileList to Array and filter the same by checking whether its type contains sub-text 'image'.

   var files = e.target.files;
   files = [...files].filter( s => s.type.includes("image") )

Demo

document.querySelector( "[type='file']" ).addEventListener( "change", function(e){
   var files = e.target.files;
   files = [...files].filter( s => s.type.includes("image") )
   console.log(files);
})
<input type="file" accept="image/*" webkitdirectory directory multiple>

Edit

If spread operator is not supported in your browser, then use one of the following

files = Array.from(files).filter( function(s){ 
    return s.type.includes("image") ;
});

Or

files = [].slice.call(files).filter( function(s){ 
    return s.type.includes("image") ;
});
like image 164
gurvinder372 Avatar answered Feb 06 '23 15:02

gurvinder372