A guide to uploading multiple files in Angular 6 using the ADDMORE button

Greetings everyone! I'm currently facing a challenge with uploading multiple files in a single form which includes an array of objects with files. While handling a single file upload is straightforward, dealing with multiple files in an array poses a different scenario. I'm using Angular reactive forms for a dynamic form and I am wondering how I can render the FormData object with an array of objects containing files. Furthermore, I need to know how to send all the data to the backend with a single click on the save button. The backend is implemented using Spring MVC. Any suggestions on how to achieve this would be greatly appreciated.

You can find the full source code on my Github: Source

multi-files-upload.component.html

<div class="container-fluid">
  <section class="content">
    <div id="main-form-content">
      <form [formGroup]="documentGrp" (ngSubmit)="OnSubmit(documentGrp.value)" #uploadDocumentsForm="ngForm" ngNativeValidate>
        <div class="box box-solid box-primary">
          <div class="box-body" formArrayName="items">
            <h2 class="page-header  text-blue ">
              <i class="fa fa-files-o"></i> Upload Documents
            </h2>
            <div class="row">
              <div class="col-sm-12">
                <div *ngFor="let item of items.controls; let i = index;">
                  <div [formGroupName]="i">
                    <table id="tbl-upload" class="table table-bordered">
                      <tbody>
                        <tr *ngIf="i==0" class="active">
                          <th>Document Name</th>
                          <th>Document Description</th>
                          <th>Document File</th>
                          <th>&nbsp;</th>
                        </tr>
                        <tr>
                          <td>
                            <div class="form-group required">
                              <input type="text" class="form-control" name="doc_name" formControlName="doc_name" placeholder="Enter document Category" required="">
                              <div class="help-block"></div>
                            </div>
                          </td>
                          <td>
                            <div class="form-group ">
                              <input type="text" class="form-control" name="doc_description" formControlName="doc_description" maxlength="100" placeholder="Enter document related descriptions" required="">
                              <div class="help-block"></div>
                            </div>
                          </td>
                          <td>
                            <div class="form-group  required">
                              <input type="file" name="admission_docs_path" title="Browse Document" (change)="fileSelectionEvent($event)" required="">
                              <div class="help-block"></div>
                            </div>
                          </td>
                          <td class="remove" *ngIf=" i!=0 ">
                            <a title="Remove" (click)="removeItem(i)" class="fa fa-minus-square fa-lg text-red"></a>
                          </td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>
                <div class="pull-right">
                  <a class="btn btn-sm btn-success" title="Add More" style="" (click)="addItem()">
                    <i class="fa fa-plus-square"></i>&nbsp; Add More</a>
                </div>
              </div>
            </div>
          </div>
          <div class="box-footer" style="align-content: center">
            <button type="submit" class="btn btn-primary pull-right">Save</button>
          </div>
        </div>
      </form>
    </div>
  </section>
</div>

multi-files-upload.component.ts

import { Component, OnInit, Renderer } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormArray, FormControl, NgForm } from '@angular/forms';
import { MultifilesService } from './multifiles.service'

// Component and Service code here...

Multifiles.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

// Service code here...

UploadController.java

        @PostMapping("uploadFiles")
        public String uploadMultiFiles(HttpServletRequest request)
        {
            // Controller code here...
        }

Answer №1

After experimenting with various scenarios for rendering the formdata object, I finally succeeded in one scenario.

Check out the GitHub link for the source code: Source

Here are the updated files:

multi-files-upload.component.html

<div class="container-fluid">
  <!-- Your HTML code goes here -->
</div>

multi-files-upload.component.ts

import { Component, OnInit } from '@angular/core';

// Your TypeScript code goes here

@Component({
  selector: 'app-multi-files-upload',
  templateUrl: './multi-files-upload.component.html',
  styleUrls: ['./multi-files-upload.component.css']
})
export class MultiFilesUploadComponent implements OnInit {
  
  // Your component code goes here

}

Multifiles.service.ts

Same code as provided above.

MultiFileController.java

// Your Java controller code goes here

@PostMapping("uploadFiles")
public String uploadMultiFiles(HttpServletRequest request) {
    // Your Java code goes here
    return "uploaded ";
}

If you're having trouble understanding the code, try forking it to your repository, debugging with console logs, and cloning it to gain a better understanding. Thank you.

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

Steps to configure Visual Studio Code to automatically open the original TypeScript file located in the "src" folder when a breakpoint is hit in a Node.js application

I am currently working on a CLI node application and using VSCode to debug it. Everything seems to be working fine, except for one annoyance: when I hit a breakpoint, VSCode opens the source map file instead of the actual TypeScript file located in my "src ...

Attempting to utilize a namespace-style import for calling or constructing purposes will result in a runtime failure

Using TypeScript 2.7.2 and VSCode version 1.21 with @types/express, I encountered an issue where in certain cases VSCode would report errors like: A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Interestingly ...

Retrieve the array from the response instead of the object

I need to retrieve specific items from my database and then display them in a table. Below is the SQL query I am using: public async getAliasesListByDomain(req: Request, res: Response): Promise<void> { const { domain } = req.params; const a ...

How can you create a unique record by appending a number in Javascript?

Currently, when a file already exists, I add a timestamp prefix to the filename to ensure it is unique. However, instead of using timestamps, I would like to use an ordinal suffix or simply append a number to the filename. I am considering adding an incr ...

Failed to install @ngrx/store due to unforeseen issues

Having issues with the installation of @ngrx/store My current setup includes: Node 8.9.3, NPM 5.5.1, Angular CLI 1.7.4, Angular 5.2.0 I am using Angular CLI to create a new Angular application and attempting to add @ngrx/store by running the following c ...

The constant issue persists as the test continues to fail despite the component being unmounted from the

import { render, screen } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import { act } from 'react' import Notifications, { defaultNotificationTime, defaultOpacity, queuedNotificationTime, fa ...

Utilizing String.Format in TypeScript similar to C# syntax

Is there a way to achieve similar functionality to String.Format in C# using TypeScript? I'm thinking of creating a string like this: url = "path/{0}/{1}/data.xml" where I can substitute {0} and {1} based on the logic. While I can manually replace ...

Utilize cypress to analyze the loading time of a webpage

My current challenge involves using cypress to carry out website tests. I am looking for a reliable method to measure the duration it takes for certain cypress commands to load or execute. As an example: //var startTime = SomeStopwatchFunction(); cy.visit( ...

How to retrieve the displayed text of a selected option in an Angular 7 reactive form dropdown control instead of the option value

Is there a way to retrieve the displayed text of the selected value in a drop-down list instead of just the value when using reactive forms? This is my current script: <form [formGroup]="formGroup" formArrayName="test"> <ng-container matColu ...

Tips for updating a component's state from another component in a React Native application

I have a map displaying a specific region based on the user's location. I am trying to implement a button in a separate file that will reset the map back to the user's current location while maintaining modularity. Can someone guide me on how to ...

Issue with Angular 2: Unable to download a ZIP file as a blob

It appears that the back-end functionality is working fine, as the zip file is being created without any issues: curl -X POST -H 'Content-Type: application/json' -d '{}' http://localhost:3000/zip/create > file.zip The Django back-e ...

Utilizing Angular 2 directives through an npm package

Wanting to share a directive on npm, I followed the steps in this documentation: Copied the compiled .js file from the .ts file (did not copy the map file) Created a new folder on my desktop and pasted it there Ran npm init and npm publish Started a new ...

Guide to creating two-way data binding using ngModel for custom input elements like radio buttons

I am currently facing an issue with implementing a custom radio button element in Angular. Below is the code snippet for the markup I want to make functional within the parent component: <form> <my-radio [(ngModel)]="radioBoundProperty" value= ...

Please come back after signing up. The type 'Subscription' is lacking the specified attributes

Requesting response data from an Angular service: books: BookModel[] = []; constructor(private bookService: BookService) { } ngOnInit() { this.books = this.fetchBooks(); } fetchBooks(): BookModel[] { return this.bookService.getByCategoryId(1).s ...

Tips for retrieving an object from an array with Angular and Firestore

Currently, I am attempting to retrieve an object from Firestore using the uid so that I can return a specific object as a value. I have implemented a function in order to obtain the object 'Banana'. getFruit(fruitUid: string, basketUid: string) ...

Overriding default styles in an Angular component to customize the Bootstrap navbar

Is there a way to alter the color of the app's navbar when a specific page is accessed? The navbar is set in the app.component.html file, and I am attempting to customize it in a component's css file. app.component.html <nav class="navbar na ...

Event triggered by clicking on certain coordinates

Just starting with @asymmetrik/ngx-leaflet and Angular, so this might be a beginner's issue... I'm working on an Angular.io (v5) project that incorporates the @asymmetrik/ngx-leaflet-tutorial-ngcli Currently, I'm trying to retrieve the coo ...

Mastering error handling in Angular's Http requests

In my frontend application using Angular, I need to communicate with a RESTful webservice for the login process. The webservice returns different response codes in JSON format depending on the success or failure of the login attempt: If the login is corre ...

Using Jest and Typescript to mock a constant within a function

Just getting started with Jest and have a question: Let's say I have a function that includes a const set to a specific type (newArtist): export class myTestClass { async map(document: string) { const artist: newArtist = document.metadat ...

creating interactive tabs in angular using dynamic json values

Currently I am working on a material tab feature where I aim to dynamically generate tabs based on the values from my JSON data. Below is the JSON data: [ { "regionName": "EMEA", "regionCurrency": "USD", "organizationName": "XYZ", "orga ...