How can I upload multiple images in one request using Typescript?

HTML:

<div>
  <input 
    type ="file" 
    (change)="selectFiles($event)" 
    multiple="multiple" />
</div> 

Function to handle the change event

selectFiles(event) {
  const reader = new FileReader();

  if (event.target.files && event.target.files.length) {
    const files = Array.from(event.target.files);
    
    for (let i = 0; i < files.length; i++) {
      reader.readAsDataURL(files[i]);
      
      reader.onload = () => {
        this.myModel.get('propertyName').setValue({
          fileName: files[i].name,
          fileContent: reader.result
        });
      };
    }
  }
}

I need to retrieve content from multiple selected files in one request, how can I achieve that?

Answer №1

When utilizing array-destructuring (

const [file] = event.target.files
), only the first file in event.target.files is being read. To address this, it is recommended to directly work with the entire event.target.files array and upload all files using FormData.

In your component's HTML:

<div>
  <input type="file" (change)="selectFiles($event)" multiple="multiple" />
</div>

In your component's TypeScript file:

private files: File[];

constructor(/* ... */, private backend: MyBackendService) {
  /* ... */
}

public selectFiles(event: Event): void {
  if (event.target.files && event.target.files.length) {
    this.files = event.target.files;
  }
}

// Trigger this method when submitting the form, usually on (ngSubmit)
public submitForm(): void {
  this.backend.uploadFiles(this.files);
}

In your backend service:

constructor(private http: HttpClient) {
    /* ... */
}

uploadFiles(files: File[]): void {
    const formData = new FormData();
    files.forEach((file) => formData.append(/* specify field name here */, file));
    this.http.post</* specify response type */>(/* enter API endpoint URL here */, formData).subscribe(/* handle response here */);
}

For more details, refer to this gist.

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

Exploring the File Selection Dialog in Node.js with TypeScript

Is it possible to display a file dialog in a Node.js TypeScript project without involving a browser or HTML? In my setup, I run the project through CMD and would like to show a box similar to this image: https://i.stack.imgur.com/nJt3h.png Any suggestio ...

The properties are not found in the type 'Observable<Todo[]>'

I'm currently following a YouTube tutorial and I've hit a roadblock trying to figure out where the error is originating from? Error Message: Type 'Observable' is missing properties such as length, pop, push, concat, and 25 more.ts(2740 ...

Is it possible to execute an HTTP request using a functional resolver?

Previously, I used a class-based resolver where I could inject HttpClient in the constructor. However, this approach has now been deprecated - see the source for more information. Now, I am looking to implement an HTTP get request in a functional resolver ...

Navigate through collections of objects containing sub-collections of more objects

The backend is sending an object that contains an array of objects, which in turn contain more arrays of objects, creating a tree structure. I need a way to navigate between these objects by following the array and then back again. What would be the most ...

Creating a new component when a click event occurs in React

Currently diving into the world of React while working on a project that involves mapbox-gl. I'm facing an issue where I can successfully log the coordinates and description to the console upon hover, but I can't seem to get the popup to display ...

What is the best way to trigger an event within an Angular app using RxJS in version 10?

As I venture into the world of Angular10, I find myself experimenting with a Canvas and honing my skills in drawing on it. Let's refer to the object drawn on the canvas as a "Foobar" - my Angular10 code for drawing Foobars is coming along nicely. Util ...

Error: Attempting to access the 'pipe' property of an object that is undefined in the context of Jasmine and Angular

I'm encountering an issue with unit testing in Angular. Specifically, I'm getting a TypeError: Cannot read property 'pipe' of undefined when trying to test the output of an observable subscribe function. Any assistance on resolving this ...

Resolve the result of the HttpComponent within the Service component

Consider this example involving HttpClient: In Service configData: string[]; fetchData(): Observable<string[]> { return this.http.get<string[]>('./assets/config.json'); } getConfigValue(key: string): string { if ...

What is the reason behind TS not using Symbols for enums?

When it comes to enums, ES6 symbols provide a great solution for avoiding collisions. Initially, I assumed that TypeScript's enum type used Symbols for enums if the target was set to 'es6', but it turns out it doesn't: enum Role {Emplo ...

"Error encountered while executing a code snippet using Navalia in TypeScript

I have been attempting to execute this code snippet from https://github.com/joelgriffith/navalia but despite my efforts, I have not been able to get it running smoothly without encountering errors: navaliatest.ts /// <reference path="typings.d.ts" /&g ...

Creating a fresh type in Typescript based on object keys that are already defined within an interface

Here is the scenario I am currently dealing with: interface ListField { code: number; message: string; } interface List { [key: string]: ListField; } export const allCodes: List = { FIRST: { code: 1, message: 'message 1', }, ...

Troubleshooting the tabindex issue with buttons in MatMenu in Angular

I am currently using Angular 17 in my project and I am working on adding ADA compliance to it by placing tabindex where needed. However, I am encountering an issue with a button inside a mat menu. The tabindex="0" attribute is not focusing on th ...

Generating and setting an object property in TypeScript at runtime

In my code, I have defined an interface as follows: export interface OurHistory { ourHistory?: object; step1?:object; step2?:object; } Within the HistoryComponent class, I am doing the following: export class HistoryComponent implements OnInit, On ...

Sluggish behavior detected in hybrid AngularJS and Angular application when accessed through Safari browser

Lately, I have embarked on the task of migrating an AngularJS application to Angular 4 using the upgrade module. Within my AngularJS directives, I am utilizing a third-party library (ngFlow) for file uploads via XMLHttpRequest.send(). Everything functions ...

I'm having trouble grasping the issue: TypeError: Unable to access the 'subscribe' property of an undefined object

I've been working on a feature that involves fetching data from API calls. However, during testing, I encountered some errors even before setting up any actual test cases: TypeError: Cannot read property 'subscribe' of undefined at DataC ...

NextAuth credentials are undefined and authentication is malfunctioning in React

I encountered the following issue: This is the code snippet that I am using: return ( <> {Object.values(providers).map((provider) => { if (provider.id === "credentials") { return null; } retu ...

What is the best way to guide users to a different page once they have submitted form data

On my website, users have the ability to create bundles and include custom or predefined tasks within them. Everything functions properly, allowing for fields to be edited as needed. Once satisfied with the entries, users must click the "Save" button. Upon ...

Angular 4 - The Promising Outcome: How to Retrieve the Value upon Completion

Is there a way to retrieve a value from a promise and store it in a global variable? I've been attempting to accomplish this, but the global variable remains undefined. import { Injectable } from '@angular/core'; import {ActivatedRouteSnap ...

Streamlining all icons to a single downward rotation

I am currently managing a large table of "auditpoints", some of which are designated as "automated". When an auditpoint is automated, it is marked with a gear icon in the row. However, each row also receives two other icons: a pencil and a toggle button. W ...

What is the process for recreating a thread with different parameters?

I am working on a multithreading program that sends emails to my clients. However, I am facing some issues with the threads in my code - they only close the window of Firefox and do not continue the desired actions. I am looking to create an algorithm wher ...