Tips on sorting a FileList object selected by a directory picker in JavaScript/TypeScript

I need to filter or eliminate certain files from a FileList object that I obtained from a directory chooser.

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

Within my .ts file:

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

The selectedFileList contains different types of files such as image/jpg, image/png, application/javascript, application/pdf, etc. I specifically want to retrieve a FileList Object with only image type files. How can this be achieved?

Note: The use of `accept="image/*"` in the HTML input element does not have the intended effect 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",
}

In my code I encounter the issue

error: files.slice is not a function
.

Answer №1

Utilize the spread operator ... to transform a FileList into an Array and then narrow it down by checking if its type contains the sub-text 'image'.

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

Example

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>

Modify

If your browser does not support the spread operator, you can use one of the following alternatives:

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") ;
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Show blank value if there are no search results, along with an additional menu option

I am currently working on a Typeahead feature with a customized menu using the renderMenu method. In this setup, I have added 2 custom menu items at the bottom - one divider and a button. An issue arises when there are no search results. If I do not inclu ...

Can you please explain the significance of classes <T> and <U> in Angular 2?

After diving into the Angular 2 TypeScript documentation, I have come across these two classes frequently. Can someone provide a detailed explanation of what they are? One example code snippet from the QueryList API documentation showcases: class QueryLi ...

React-hook-form does not display the input length in a custom React component

Introducing a custom Textarea component designed for reusability, this basic textarea includes a maxlength prop allowing users to set the maximum input length. It also displays the current input length in the format current input length/max length. While ...

Can you explain the distinction between ng test and ng e2e?

Concerned that someone might close my question, I struggled to find a satisfactory answer. Perhaps it's due to my limited knowledge in the Angular 2+ realm or maybe I misunderstood something. From what I gathered after dabbling in Hello World project ...

The popularity of AJAX in JavaScript is continuing to rise

I am facing an issue with my website that features a configurable 3D object with various properties. Whenever I reload the div containing the 3D object to reflect new properties, the script data keeps adding on. This not only slows down the functionality a ...

The specified timeout elapsed without the jasmine async callback being invoked

Having recently ventured into Protractor and javascript, I've encountered a persistent error that none of the existing solutions seem to shed light on. The issue revolves around understanding async callbacks within my Page Object model implementation. ...

Navigating in Angular 2 RC4 with Path Variables Containing Special Symbols

Could someone offer suggestions on how to correctly call parameters with special characters from URLs? Below is my current code for calling the parameter: ngOnInit() { this.route.params.subscribe(params => { let accountrefID = params ...

Why is it that one of my useQuery hooks is returning a value while the other one is returning undefined?

I'm currently facing an issue with React Query where one of my useQuery hooks is logging undefined while the other one is displaying the correct data. Both functions are async and perform similar tasks. I've been troubleshooting this problem for ...

Click on the button to generate a PDF report using Internet Explorer 11

After encountering some challenges with printing a PDF report specifically on IE 11, I am reaching out for help. The code snippet below works perfectly in Chrome, but when it comes to IE 11, everything falls apart. Just to provide some context, I am develo ...

The ng-repeat functionality in Angular 2 is not functioning correctly when trying to select an option from an array of objects. Instead of displaying the actual object, it is

When using ngRepeat in Angular 2, I have found that selecting options from an array of strings works perfectly fine. However, when the data is an array of objects, the ngModel displays '[Object object]' instead of the selected object. I have trie ...

When the keyboard appears, the Ionic 2 form smoothly slides upwards

I am currently working with the most recent version of Ionic 2. In my code, I have a <ion-content padding><form></form></ion-content> containing a text input. However, when attempting to enter text on an Android device, the keyboard ...

"Utilizing Typescript's keyof operator on its own

I'm grappling with the challenge of creating a type that can utilize the typeof its own keys, but I'm hitting a roadblock. Below is a simplified version of what I'm attempting to achieve: type SpecialType = Record<string, (getter: <K e ...

Send a value to several PHP pages simultaneously using JQuery

I find myself asking this question due to my lack of experience. Is it possible to send a value to multiple PHP pages using JQuery? Let me illustrate what I am attempting to achieve. $(function() { $("#account").change(function() { $("#facilities" ...

The timer freezes briefly at 1:60 before switching to 1:01

I'm in the process of creating a website for Rubik's cube scrambling and timing, and everything seems to be working well so far. I have implemented a scrambler, a timer, and a list of recorded times (still a work in progress). The timer is functi ...

Transform Loopback 4 filter into a SQL WHERE condition

When using Loopback 4, the filter object that is received by functions like Get and Count appears as shown below: { where: { property: { op: value; } } } I am interested in converting this structure into an SQL WHERE clause to use it in ...

The local storage gets wiped clean whenever I am using this.router.navigate

I am in the process of building a website using Angular 5 and Typescript. One important aspect of my implementation is utilizing localStorage to store the JWT Token for user login. Whenever I click on a link (either Home or any other link), I implement a ...

The default route in Angular is always preloaded and ready to be

I currently have two routes available: home [ '' ] about [ 'about' ] Upon directly accessing the /about route in my browser, I've observed the following: The home module is preloaded even though I requested /about. The URL gets ...

How to manage UNC paths and "mapped network drives" within an Electron application?

I have developed a cross-platform (macOS-Windows) app using Electron that functions smoothly with files and media assets from a local drive. However, it encounters issues when dealing with UNC paths and "mapped network drives". Since I am a contractor, I d ...

The $.inArray() function returns a value of false or -1, despite the fact that the variable

My goal is to verify that my currentMedia variable (which exists in the DOM) can be located within my array media, and then return the index i, which should be 0 instead of -1. When I execute console.log(media[0]); and console.log(currentMedia);, the outc ...

What is the best way to retrieve the 'date,time' column from a MySQL database and use it as input for the google chart DateRangeFilter?

I am facing an issue with a column in my dataset that contains date-time values, such as '2017-2-2 10:30:20'. I need to use these rows as an input for a Date Range Filter in Google Chart. Can someone guide me on how to achieve this? I attempted ...