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

Discover the #ID and apply AddClass through the URL in the Navigation Jquery

I am currently in the process of developing a website and I am looking to navigate from one link to another using IDs. Here is an example of what I am trying to achieve: Page Name: index.html <a href= "collection.html#rings">Rings</a> Page N ...

Angular - Dropdown menu fails to display options

I encountered an issue with the JSON response from my Angular-12 API endpoint: { "message": "vehicle Model Detail.", "error": false, "code": 200, "results": { "vehiclemakes": [{ ...

Building a flexible table in React JS based on specific keys: a complete guide

I'm currently working on developing a dynamic table component using React JS. The component at the moment has a fixed header with the most common result keys. Some results contain additional information such as phone numbers and degrees. I'm loo ...

Showing the image as a backdrop while scrolling through text

How can I create an effect that continuously displays the image while scrolling text in Internet Explorer without using position: sticky or position: fixed? var sticky = document.querySelector('.sticky-container'); var img = document.querySele ...

Freezing objects using Object.freeze and utilizing array notation within objects

Could someone kindly explain to me how this function operates? Does [taskTypes.wind.printer_3d] serve as a method for defining an object's property? Is ["windFarm"] considered an array containing just one item? Deciphering another person& ...

Using jQuery to toggle visibility based on data equivalence

I created a code snippet in which I am implementing jQuery show/hide functionality when the data attribute matches. Here is the HTML structure: <div class="container"> <div class="item" data-item="1">1 <div class="inside" data-c ...

Creating a typescript type for contextual dispatch by leveraging the values of another interface

I am seeking to define a specific type for my "reducer" function. The "reducer" function I have takes in 2 parameters: the current state and the data sent in the dispatch context (to be used by the reducer). const reducer = ( state: any, props: { ...

What is the most effective way to retrieve the value of a child component in Angular 2 and pass it to the parent component?

I am working on a project with a child component (calendar) and a parent component (form). I need to select a value in the calendar and then access that value in the form component. What is the best way to achieve this? Child Component.ts: import { ...

Is it possible to attach "traits" to a current array of objects using TypeScript?

I have a variety of object types that I need to manipulate within an array consisting of those object types. type AB = { a:number, b:number} type CD = { c:number, d:string} type DE = { d:number, e:boolean} let state: AB[] = [] function onStateChange(newSt ...

What is the best way to send a string without using quotation marks as a parameter in a function?

If I have an API that takes the query as http://localhost:8000/api/v1/rental/?place__startswith=kathmandu, how can I implement a generic search in ReactJS? What I attempted to do is pass the default parameter as search(query=kathmandu) so that the result ...

Iterating over an object using ng-repeat in Angular, where the value is an array

In my data object, I have key-value pairs where the value is an array. Each array contains objects with various properties. $scope.testObj = { "London":[ {"id":1,"city":"London","country":"GB","name":"Test1"}, {"id":4,"city":"London" ...

React Select feature fails to show suggestions after asynchronous debounced call

I am currently utilizing react-select to load results from an API while debouncing queries using lodash.debounce: import React, {useState} from 'react'; import AsyncSelect from 'react-select/lib/Async'; import debounce from 'lodas ...

Strange symbols were stored in the database after saving the textarea value

After submitting a form, text entered into a text area is being saved to my database. However, in one instance, certain characters such as • are appearing in the field. For example: • Text When retrieving the data from the database using Jav ...

Using an array as the source for your Mui Autocomplete instead of JSON

I'm attempting to recreate the autocomplete MUI example shown here, but with a slight variation. Instead of utilizing a JSON data structure, I am simply passing an Array. Here is what I have tried: export default function SearchTutorialArray() { con ...

Unable to adjust the width of a table column within a horizontally scrollable container

I am struggling to resize the columns of a large table with 20 headers. Despite trying to place the table inside a div with overflow:auto, I still cannot achieve horizontal scrolling or make the div expand when resizing the columns. A sample code snippet ...

issues with the functionality of bootstrap modal

I'm currently working on a project where I need to set up a modal popup using bootstrap. The website I'm working on is organized by departments, so the only part of the code that I have control over is the main body of the site. I have included t ...

Navigating UnwrapRefSimple in Vue Composition API and TypeScript: Best Practices

When I utilize reactive objects in Vue Composition API, I encounter Typescript errors relating to UnwrapRefSimple<T>. This issue appears to be specifically tied to using arrays within ref(). For instance: interface Group<T> { name: string ...

Anchoring HTTP headers in HTML tags

Currently, I am working on some code to enable dragging files from a web app to the desktop by utilizing Chrome's anchor element dragging support. The challenge I am facing is that certain file links require more than a simple GET request - they nece ...

Ways to eliminate unnecessary items from a JavaScript object array and generate a fresh array

My JavaScript object array contains the following attributes: [ { active: true conditionText: "Really try not to die. We cannot afford to lose people" conditionType: "CONDITION" id: 12 identifier: "A1" ...

Retrieving Content within <b></b> Tags from an RSS Feed XML (with Javascript/React)

After parsing an RSS Feed from Upwork, I have extracted job item data points such as title and link. However, a significant amount of the necessary information about each job (category, skills, etc) is buried within the "content" data item as one large blo ...