Why is FileList.item giving me an error?

Why am I getting an error saying the item property of a FileList variable is not a function?

To clarify, I retrieve all files from a file input and store them in an array as type FileList successfully:

files: any = [];

onImageSelect(files: any = FileList) {
    for(let i = 0; i < files.length; i++) {
      this.files.push(files.item(i));
    }
    console.log(this.files)
  }

The above onImageSelect method executes when the file input changes:

<input type="file" accept="image/*" multiple #fileUploader id="fileUploader" (change)="onImageSelect($any($event.target).files)">

Now that I have an array of selected files stored as type FileList, I aim to upload each file to Firebase by adding them to a NEW array also as type FileList:

filesUploaded: any = [];

uploadImages(selectedFiles: any = this.files) {
    for (let i = 0; i < selectedFiles.length; i++) {
      this.filesUploaded.push(selectedFiles.item(i));
    }
  }

The uploadImages method mentioned above is triggered on button click:

<button mat-raised-button color="secondary" (click)="uploadImages()">Upload</button>

However, upon execution, I encounter a type error message stating "ERROR TypeError: selectedFiles.item is not a function". What could be causing this issue?

Answer №1

Consider utilizing this alternative approach:

handleSelectedImages(filesArray: any): void {
    this.chosenImages = filesArray.target.files;
    const formDataToSend: FormData = new FormData();
    for (let num = 0; num < this.chosenImages.length; num++) {
      formDataToSend.append('image' + (num + 1), this.chosenImages[num]);
    }
    console.log(formDataToSend);
  }

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

Explore a collection of entities

Here's the object I'm dealing with: Object myobj = new[] { new MyClass(), new MyClass() }; Is there a way to access it as an array? I attempted to use ((Array) myobj)[0] but it resulted in an error: ((Array) myobj)[0] Cannot apply ...

I'm confused about how to make sure each child in a list has a distinct 'key' prop, it's important for proper rendering

Hey there! So I've got this assignment from school that involves fetching data from randomuser.me. I followed all the steps given to me, but ran into an issue when a warning popped up in the terminal. The project compiled successfully and is running f ...

Is the utilization of the React context API in NextJS 13 responsible for triggering a complete app re-render on the client side

When working with NextJS 13, I've learned that providers like those utilized in the React context API can only be displayed in client components. It's also been made clear to me that components within a client component are considered part of the ...

What is the best way to convert this tsc script into an npm script in package.json?

I am looking to execute the following script as an npm script: tsc src/*.tsc --outDir bin When I run this command directly in the terminal, it works as expected. However, when I add the exact same script to my package.json: { "scripts": { ...

Display the toggle button for expanding/collapsing text only when the length of the string exceeds 50 characters

Is there a way to only show a "read more/less" button in a table if the content exceeds 50 characters? The table contains a mix of content, some short announcements with about 10 characters and others with over 100. <div class="col"> <span ng-c ...

How is the process of connecting a database to REST through a join operation?

I've got a database featuring two tables, namely orders and orderProducts, connected through a 1:n relationship. My goal is to merge these two tables and present the data in JSON format to my REST tool. To accomplish this, I'm utilizing the foll ...

What are some ways we can customize the user interface for mat-select dropdowns?

I am looking to create a dropdown menu with a header containing 3 columns (ID, Model, Description). While I am familiar with creating a simple dropdown using mat-select, <mat-select> <mat-option> a </mat-option> <mat-option&g ...

Using Angular 2 in combination with three.js OrbitControls allows for enhanced

Exploring the integration of a threejs example within my Angular (CLI) 2 application. First, I installed threejs using the command: npm install three --save Then, I added typings with this command: npm install @types/three --save-dev After completin ...

The 'connectedCallback' property is not found in the 'HTMLElement' type

After taking a break from my project for a year, I came back to find that certain code which used to work is now causing issues: interface HTMLElement { attributeChangedCallback(attributeName: string, oldValue: string, newValue: string): void; con ...

Uniquely Randomized Number Generator in C++ without repeats

Can you help me create an algorithm implementation in C++ that generates random numbers for a table without repeats or lists? I attempted to write the code myself, but it stops working when I input n=32769. It works fine within the range of 0-32768. Any s ...

Access-Control-Allow-Methods does not allow the use of Method PUT in the preflight response, as stated by Firebase Cloud Functions

I am facing an issue with my Firebase cloud function endpoint. I have a setup where it forwards PUT requests to another API endpoint. I have configured the following Access-Control-Allow- headers: // src/middlewares/enableCORS.ts export default function en ...

Utilize Angular's ng-repeat directive to iterate through this JSON data structure for implementing user-to

Struggling with the user-to-user messaging interface on an app and having difficulty using ng-repeat on the items. Here is the provided data: { "ID": 4118, "CreatedDate": "2015-08-20T03:12:50.397", "recipient": [ { ...

What is the reason behind not being able to perform a null check on an array entry in Typescript

I've got an array filled with objects that may be either null or a Gamepad: let devices: (Gamepad | null)[] = navigator.getGamepads() If the first item in the array happens to be a valid Gamepad, I need to perform a specific action: let device: Gam ...

Having trouble retrieving information from hash fetch fragment following authentication redirection in Angular 4

Once the authorization process is complete, the browser will be redirected to the following URL: &token_type=bearer&state=XYZ&expires_in=3599 However, just before I can retrieve the details, everything seems to disappear and the browser' ...

Mapping an array of JSON objects into a plain JSON object in TypeScript Angular 2: A Guide

Response Data: [ { "professionalId": { "cib_code": "30003", "thirdPartyId": "RS30004" }, "nationalIdentifier": "984538926", "nationalIdType": "SIREN" }, { "professionalId": { "cib_code": "30003", "thirdPar ...

Currently, I am attempting to implement password strength validation using Angular

Looking for a way to implement password strength validation in Angular? You may encounter an error message like this: NullInjectorError: No provider for password strength! in the passwordstrength.ts file HTML <div class="validation_errors t ...

Using TypeScript to transform a tuple type into an object

When dealing with a tuple type like: [session: SessionAgent, streamID: string, isScreenShare: boolean, connectionID: string, videoProducerOptions: ProducerOptions | null, connection: AbstractConnectionAgent, appData: string] there is a need to convert it ...

`AngularJS Voice Recognition Solutions`

In my quest to implement voice recognition in an AngularJS application I'm developing for Android and Electron, I've encountered some challenges. While I've already discovered a suitable solution for Android using ng-speech-recognition, fin ...

Having Trouble Retrieving Data from Observable in Angular 2 and Typescript

I've encountered a promise error when trying to access a variable that receives data from an observable. Here's an example: Within my component, I have defined the Stat class: export class Stats { name: string; percentage: number; constru ...

A guide on extracting the values of checked checkboxes by their ID using javascript

I'm currently attempting to extract the values of selected checkboxes. These checkboxes have distinct IDs because they are specified within a modal window. <input type = 'checkbox' id = 'audience_Name-$row[asset_ID]' value = &a ...