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

Mastering date selection in Angular 4 - Restricting days in the past and future

I am looking to restrict selection of future and past dates using an Angular 4 Date-Picker. I only want to enable the current date [today]. How can I accomplish this? Does anyone have any suggestions or ideas? This is the template I am currently using: ...

Attention! Circular dependency has been detected during compilation with warnings

Every time I attempt to build my project, an error is thrown- WARNING in Circular dependency detected: src\app\own-filter\own.filter.module.ts -> src\app\own-filter\own.filter.component.ts -> src\app\own-f ...

How to access the state of an @ngrx/data entity in a reducer function in ngrx 8

I am trying to access the state of a ngrx/data entity within a reducer function. Currently, I am working on implementing a pager (pagination) feature where users can navigate through different pages. However, I am facing a challenge in determining the tot ...

What is the reason that Gatsby's arrow function is unable to access a value from props that is calculated from a promise?

Could someone shed light on why the key value is showing as undefined within the arrow function: // in parent component const Parent = () => { const [key, setKey] = useState<string>(); // this contains an expensive function we on ...

Mixing pipe operators with Angular Observables in an array

In my project, I have an interesting scenario where I am using Observables and piping them to multiple functions as shown below. getOrders(filters: any, page: any = 1, orderBy: string = 'deliver_on', sort: string = 'asc') { const op ...

Navigating through a typescript array containing various types and mapping each element

Is there a way to get [valueOfTypeOne, ValueOfTypeTwo] instead of (valueOfTypeOne | ValueOfTypeTwo)[] for each resulting element in this scenario? const [valueOfTypeOne, ValueOfTypeTwo] = await Promise.all( [ fetchTypeOne(), fetchTypeTwo( ...

Utilizing object as props in ReactJS with TypeScript

I'm new to working with ReactJS, and I made the decision to use typescript for my current project. The project is an application that fetches movies from an API and displays them. Take a look at the app: import React from 'react'; import &a ...

The element 'mat-form-field' is unrecognized: 1. Confirm if 'mat-form-field' is an Angular component and ensure it is included in this module

I've been struggling to configure Angular material components in my project. Whenever I try to use mat-input, I encounter errors even after importing all the necessary dependencies. Here is a snippet of the code within my component: <form class="e ...

Testing a component in Angular 2 that utilizes the router-outlet functionality

I recently set up an angular 2 project using angular-cli. As part of the setup, I created a separate AppRoutingModule that exports RouterModule and added it to the imports array in AppModule. Additionally, I have the appComponent which was generated by an ...

What could be causing my React Redux state to not trigger a re-render?

Having trouble with my redux state not triggering a re-render when using a selector. I'm new to react-redux and typescript, and despite following advice online about returning a new object from the reducer, my object is still not re-rendering even tho ...

Converting Angular 5 select option values to strings is a must

I have set up a basic select connected to a variable like this: <select id="client" name="client" [(ngModel)]="order.clientId"> <option *ngFor="let client of clients" [value]="client.id"> {{ client.name }} </option> </ ...

Oops! An issue occurred: The value 'NgxMatDrpModule' was not expected in the specified file path: node_modules/ngx-mat-daterange-picker/ngx-mat-daterange-picker.d.ts

Encountered an error while building an Angular 7 app using the command ng build --configuration=dev. The exception shows a single quote prefixed to NgxMatDrpModule. Even after deleting node_modules, package-lock.json and reinstalling node modules, the issu ...

angular5: The ngFor directive will only function properly after the second button click

Here is my current situation: 1) When the user inputs a keyword in a text field and clicks on the search icon, it triggers an HTTP request to retrieve the data. 2) The retrieved data is then rendered in HTML using ngFor. The issue I am facing is that up ...

An error has occurred during the Next.js build process: ReferenceError - The component is not defined

Encountering an error during the yarn build process, but no issues with yarn dev My Typography component is custom-made, and I utilize absolute imports with the baseUrl option in tsconfig.json next version: v9.5.2, typescript version: 3.9.7 See error ou ...

Tips for converting a JSON array into a Java Object with GSON

I am currently working with a JSON document that needs to be parsed. Although I am displaying only two objects in the files array, typically there are more than 500 objects present. { "files":[ { "name":"/testing01/partition_395.sh ...

Encountering an issue while trying to utilize Vuex in Vue with TypeScript

I recently utilized npm to install both vue (2.4.2) and vuex (2.3.1). However, when attempting to compile the following code snippet, I encountered the following error: https://i.stack.imgur.com/0ZKgE.png Store.ts import Vue from 'vue'; import ...

Why am I getting a null value for my Array when I should be expecting an Object instead?

I have been attempting to create an Array that contains objects for a project, but I keep encountering an error message stating: "this.allgmArray is undefined". However, it is not actually undefined: allgmArray: DialogBook[]; [...] load(){ for(var i ...

Is there a way to update the Angular component tag after it has been rendered?

Imagine we have a component in Angular with the selector "grid". @Component({ selector: 'grid', template: '<div>This is a grid.</div>', styleUrls: ['./grid.component.scss'] }) Now, when we include this gri ...

What could be causing input to be blocked in certain situations while using my Angular directive with compile function?

Recently, I created a directive that adds a class based on a certain condition. You can find the code snippet at the end of this question. The directive functions as expected in a simple use case where it's applied to a required field: <input typ ...

What is the best way to play AudioBuffer on an iPhone device?

When retrieving audio data from a stream, I encounter an issue with playing audio on iPhone Safari. The sound does not play unless I allow mediaDevice access for audio. Is there a way to play the audio without having to grant this permission? This is the ...