How to use Angular 8 Form Builder to upload an array of multiple images

My product form includes various fields like product name, description, and an array of images.

Product Form

Product Name - Product Description

Product Purity - Product Commodity

Images (Add)

Checkbox 1 - Image 1

Checkbox 2 - Image 2

Checkbox 3 - Image 3.

...

I can successfully save the product name, product description, and other fields in my database, but I am unsure how to upload those images. The images are generated by clicking the add button, and there may be one or multiple images based on requirements. I have created the form using a Form Builder. Below is my code:

Template :

<form  class="kt-form kt-form--group-seperator-dashed" [formGroup]="mmgForm">
      <!-- Form content here -->
  </form>

Ts File :

// TypeScript code here

Answer №1

To address this issue, my recommendation would be to establish a specific FileUploadService.

The approach taken by the Service:

uploadFiles(Array<File> files): Observable<FileUploadResponse> {
    const url = `your-upload-url`;

    const formData: FormData = new FormData();

    for(File file in files) {
        formData.append('file', file, file.name);
    }

    return this.http.post<FileUploadResponse>(url, formData /*{headers if necessary}*/);
}

Your component.ts:

//[..]
Array<File> files = [];

onFileInputEvent(event: any) {
  for(let i = 0; i < event.srcElement.files.length; i++) {
    this.fileName = event.srcElement.files[0].name;
    this.files.push(event.srcElement.files[0]);
  }
}

uploadFiles(){
  this.fileUploadService.uploadFile(this.file).subscribe(res => { // do something}, err =>{});
}

Your component.html:

<!-- [..] -->
<input id="fileInput" placeholder="Images" type="file" (change)="onFileInputEvent($event)" accept=".jpg">

Enhance the input elements for a more visually appealing look:

<div class="file-input">
    <input id="fileInput" placeholder="CSV-Datei" type="file" class="hidden" (change)="onFileInputEvent($event)" accept=".csv">
    <label for="fileInput" class="mat-raised-button">Add images</label>
    <mat-chip-list *ngIf="fileName">
        <mat-chip [removable]="true" (removed)="remove()">
            {{fileName}}
        <mat-icon matChipRemove>cancel</mat-icon>
    </mat-chip>
</mat-chip-list>

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

Is it possible to change XML using Ajax technology?

Is it possible to update a value in an XML file using JavaScript/Ajax? I've managed to access the XML file with Ajax and utilize its values in my script. Now, I want to send any updates made by the script back to the XML file on the server using Ajax ...

Tips for broadcasting the blob

I am currently working on a radio system project that involves streaming live audio from a microphone to the user in real-time. However, I am new to using node.js and unsure of how to achieve this. Can anyone provide guidance on how to stream the audio fro ...

What is the reason behind the failure of this code to check for anagrams?

I am attempting to create a JavaScript function that checks for anagrams. To keep things simple, let's assume this function only works with lowercase strings that do not contain spaces, numbers, or symbols. Why isn't the following code functionin ...

What is causing my Node JS app to only show the initial JSON object?

Having an issue with my Node application while writing a JSON object and integrating the Twilio API. The console log displays all objects properly, but when written to the document, only the first object is visible. Can anyone help me figure out why this d ...

Replicated shadows brought to life in three.js

I've been experimenting with shadows in three.js and have encountered a problem where the shadow is being cast on two faces of a mesh, as shown here. It's puzzling that the shadow from the "head" of my character is appearing on two faces of the ...

What is the best way to include temporary attributes on a mongoose object solely for the purpose of a response, without saving them to the database

I am looking to add extra temporary properties with additional data to the response but have encountered some difficulties. 'use strict'; var mongoose = require('mongoose'); var express = require('express'); var app = expres ...

execute a script using an npm module

Imagine having a function like this index.js greet = () => { console.log('hello'); } greet(); and you want it to execute as soon as the page loads, so you include greet();. This works fine when the file is imported in your index.html in ...

Is there a way to determine if the current path in React Router Dom v6 matches a specific pattern?

I have the following paths: export const ACCOUNT_PORTAL_PATHS = [ 'home/*', 'my-care/*', 'chats/*', 'profile/*', 'programs/*', 'completion/*', ] If the cur ...

Is there a way I can invoke my function prior to the form being submitted?

For the last couple of days, I've been struggling to make this code function properly. My goal is to execute a function before submitting the form to verify if the class for each variable is consistent. You can access my code here. Any assistance you ...

Angular Recurring Request

Currently, I am using Angular5 and making requests every 5 seconds to check the status of a task. However, I would like to implement a more flexible condition where if the request receives a status code of 202, continue sending requests, but if it receives ...

Having issues with the custom listing feature in Jquery UI auto complete not functioning as expected

I am facing an issue with my implementation of jquery UI autocomplete. The autocomplete functionality is not working as expected, despite the absence of any JavaScript errors. Below is the JSON data that I am working with: {"d":"[{\"label\":&bs ...

The React component fails to display updates following a state change

Greetings, I am currently facing an issue with re-rendering the component. Below is the code for the initial screen where a custom component is being utilized: class Ahelle extends React.Component{ constructor(props){ super(props) this. ...

Are there any find all functions available in JavaScript that are built-in?

I frequently work with arrays in JavaScript, and I am facing an issue with the function .find() as it only returns the first occurrence. I need a way to get all occurrences if there are multiple. Below is my code: const condition = [ { info_p ...

When utilizing res.redirect in Express, an error is triggered stating "Uncaught SyntaxError: Unexpected token <""

Utilizing Node.js, Express, Socket.io, firebase admin+auth, and Handlebars. An error Uncaught SyntaxError: Unexpected token < keeps popping up. Whenever I use res.redirect('/login');, I encounter the error. It disappears when I remove res.re ...

retrieving information via AJAX call using jQuery

I've been tasked with customizing a book website, and I'm trying to integrate reviews from the Goodreads API. However, my Ajax request isn't returning any data. Here is the code snippet: $.ajax({ 'type': 'GET', & ...

I am looking to create a unique JavaScript variable within my GTM container that will automatically return a value of true when the user approves sharing

Is there a way to trigger a tag when the user shares their location with the browser? I attempted using the following code within a custom JavaScript variable in my GTM Container, but it didn't seem to work. navigator.permissions && navigator ...

"Continue to shine until the rendering function displays its source code

I've encountered a strange issue where I'm using lit until to wait for a promise to return the template, but instead of the desired output, the until's function code is being rendered. For example: render() { return html` <div c ...

The issue of declaration merging and complications with nested node_modules

Here is the structure I am working with: @my/app node_modules @types/angular @types/angular-translate @my/library node_modules @types/angular The issue arises from the fact that @types/angular-translate extends the definitions of @types/angular ...

The Angular component is failing to display the template

After following a tutorial on UI-Router () I have implemented the following states in my Angular application: angular .module('appRoutes', ["ui.router"]) .config(['$stateProvider', '$urlRouterProvider', function($sta ...

How to enable drag-and-drop functionality for an iframe?

I've successfully made a chat widget draggable using react-draggable. However, the chat widget is also consumed by an iframe created entirely with HTML. I need the iframe to be draggable as well, but react-draggable doesn't support this. Are ther ...