I am attempting to send an array as parameters in an httpservice request, but the parameters are being evaluated as an empty array

Trying to upload multiple images involves converting the image into a base64 encoded string and storing its metadata with an array. The reference to the image path is stored in the database, so the functionality is written in the backend for insertion.

However,

  1. When processing image files into base64 and storing metadata using an array as arguments passed to a function, an empty array is received in the service call. Can someone help me understand why and how to fix this?
  2. The upload image is being called for every iteration of the for loop, but why?

Thanks in advance.

export class ItemsDetailsComponent {
  //image variables
  itemImageDetails: any = [];
  ItemImageURLs: any = [];
  itemImageCount: number = 0;
  base64image: any = [];
  CustImageData: any;
  itemImageData: any;
  itemimagePath: any;
  fileList: any = [];
  newImageMetaData: any = [];
  imageMetaData: any = [];
  addImagePopupVisible: boolean = false;
  deleteImagePopupVisible: boolean = false;
  tempImageCount: number = 0;
  deleteImageURL: any;
  deleteImageName: any;
  deleteImageConfirmPopUp: boolean;
  value: any[] = [];

  constructor() {
    // ...
  }

  processFile() {
    let count = 0;

    for (let i = 0; i < this.value.length; i++, count++) {
      this.fileList.push(this.value[count]);
      this.httpDataService.getBase64(this.value[count])
        .then(base64img => {
          this.base64image[this.tempImageCount] = base64img;
          this.base64image[this.tempImageCount] = this.base64image[this.tempImageCount].split(",")[1];
          this.tempImageCount++;

          this.newImageMetaData.push({
            "type": this.fileList[i].type,
            "name": this.fileList[i].name,
            "size": this.fileList[i].size
          });

        });
    }

    this.uploadImages(); 
  }
  
uploadImages() {
  if (this.newImageMetaData.length == this.base64image.length) {

    console.log(this.newImageMetaData);
    console.log(this.base64image);

    this.httpDataService.uploadMultipleImages(["", this.itemCode, [...this.base64image],
        [...this.newImageMetaData]
      ])
      .subscribe(status => {
        if ((status != -1) && status) {
          this.toastr.success(status + "Image(s) Successfully Uploaded");
          this.getImag();
          this.getItemImageDetails();
          this.newImageMetaData = [];
          this.base64image = [];
        } else {
          this.toastr.error("Error Uploading image" + status + " Image(s) Uploaded ");
        }

        this.addImagePopupVisible = false;
      });
  }

}

<div class="widget-container">
  <form enctype="multipart/form-data">
    <dx-file-uploader #fileUploader [multiple]="true" accept="image/*" [(value)]="value" uploadMode="useForm"></dx-file-uploader>
    <div class="content">
      <div *ngIf="value.length > 0">
        <h4>Selected Files</h4>
      </div>
      <div *ngFor="let file of value">
        <div class="selected-item">
          Name:
          <span>{{file.name}}</span><br /> Size:
          <span>{{file.size}}</span>bytes<br /> Type:
          <span>{{file.type}}</span><br /> Last Modified Date:
          <span>{{file.lastModifiedDate}}</span>
        </div>
      </div>
    </div>
    <dx-button text="Create Product" type="submit" (onClick)="uploadImages()">
    </dx-button>
  </form>

</div>
<div class="options">
  <div class="caption">Options</div>
  <div class="option">
    <dx-check-box text="Allow multiple files selection" [(value)]="fileUploader.multiple"></dx-check-box>
  </div>
</div>

Answer №1

  • To enhance the effectiveness of dx-button as a Call To Action, consider eliminating the action="uploadImages()" from the form tag. Instead, allow it to be triggered once processFile() finishes its iteration.

  • By maintaining both an action and a submit button within a form, the button click may execute unexpectedly.

OR

  • Opt to remove onClick from the button and update uploadImages() to processFile() in the form tag.

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

Determine the quantity of items that meet specific criteria

The initial state of my store is set as follows: let initialState = { items: [], itemsCount: 0, completedCount: 0 }; Whenever I dispatch an action with the type ADD_ITEM, a new item gets added to the items array while also incrementing the count in ...

Displaying information in form using ajax within the laravel framework

I am currently utilizing ajax to retrieve data from a database. While I am able to successfully retrieve the data on the backend, I am facing difficulties displaying it in the input field below. I have tried writing some code, but it seems that the JavaScr ...

Enabling visibility of overflowing text in dynamically inserted divs without using scroll bars

Is there a way to set the text overflow to visible without scroll bars in dynamically added <div>s? Despite what the documentation says, it doesn't seem to be the default behavior and I'm struggling to understand why. Adding text directly t ...

Retrieve the page dimensions from a Material UI component `<DataGrid autoPageSize/>`

When utilizing <DataGrid autoPageSize/>, as outlined in the documentation, you can have a Material UI table that adjusts its page size based on the browser height. However, if you are fetching data from the server progressively, it becomes essential ...

Error: Unable to access the 'offsetTop' property of null

I attempted to implement a scroll effect in my project. The goal was for users to be taken to a specific section when they clicked on an option in the navbar. However, I encountered an error during implementation. Below is the code snippet where the error ...

Use Google Maps and MySql to retrieve specific markers within a designated radius using unique latitude and longitude coordinates

Can the latitude and longitude of specific coordinates within a certain radius be retrieved from a database? ...

Angular encountered an error: spawn UNKNOWN was not handled

Within my Angular-13 project, everything had been running smoothly. However, out of nowhere, I encountered an error when trying to run ng serve: An unhandled exception occurred: spawn UNKNOWN See "C:\Users\JOSHU~1.IBE\AppData\Local ...

Encounter an error when reading a stream with a maximum timeout value set

I have encountered a challenge while trying to read and process large CSV files. Due to a rate limit in processing, I need to introduce a 1-minute delay between each request. Initially, I attempted to use set timeout, but discovered that there is a limitat ...

Encountering difficulty in retrieving the outcome of the initial HTTP request while utilizing the switchMap function in RxJS

My goal is to make 2 HTTP requests where the first call creates a record and then based on its result, I want to decide whether or not to execute the second call that updates another data. However, despite being able to handle errors in the catchError bl ...

Exploring how to set dropdown menu width for Angular2 mat-select options

Currently, I am using the angular2 mat-select control and facing an issue with the width and position of its dropdown list menu. By default, it is wider and overflows the element on both sides by a few pixels. I have not found any option for adjusting the ...

An incorrect object was removed from the array

Having an issue where the wrong item is getting deleted from an array in my component's state. Here is a simplified version of my parent Component: export default class BankList extends Component { state = { banks: [new Bank("Name1"), new ...

What is the best approach for creating a test that can simulate and manage errors during JSON parsing in a Node.js

My approach to testing involves retrieving JSON data from a file and parsing it in my test.js file. The code snippet below demonstrates how I achieve this: var data; before(function(done) { data = JSON.parse(fs.readFileSync(process.cwd() + '/p ...

Retrieving Gravity Forms AJAX Confirmation Message programmatically in JavaScript instead of displaying it

I have set up the Gravity Forms plugin in my Wordpress website and implemented the AJAX feature on my form. Currently, upon submission, a Confirmation message is displayed automatically. However, I am interested in retrieving the content of this message us ...

Exploring the versatility of Angular 4 by implementing a switch feature with

My goal is to have the menu change based on the click of the "Cadastros" action, but it seems like the issue lies with the "workspaceSelected" property not being visible to all components. I believe the best approach in this situation would be to have the ...

What could be the reason for the Express function Router() returning a value of undefined?

Currently, I am working with TypeScript and Express to develop an API that adheres to the principles of Clean Architecture. To organize my application, I have structured each route in separate folders and then imported them all into an index.ts file where ...

Nested Tab Generation on the Fly

My goal is to create dynamically nested tabs based on my data set. While I have successfully achieved the parent tabs, I am encountering an issue with the child tabs. Code $(document).ready(function() { var data1 = [["FINANCE"],["SALE"],["SALE3"]]; var da ...

Creating interactive web applications with Python Flask by utilizing buttons to execute functions

When the button is clicked in my Flask template, I want it to trigger a Python function that I defined in app.py. The function should be accessible within the template by including this code where the function is defined: Here is an example function in ap ...

Error message: "SyntaxError: Unexpected token import was not caught by the foundation"

I have recently taken over development from a previous developer who integrated Zurb Foundation as a framework into our website. The Foundation framework was installed using npm. I am encountering errors in the console related to all of the foundation java ...

Why aren't the child route components in Angular 6 loading properly?

I have encountered a small problem. I developed an app using Angular 6 with children routes implemented like this: { path:'pages', component:DatePagesComponent, children : [ {path:'404', component:Error404C ...

Developing a dynamic user interface using an Angular framework and populating it with

I am currently learning Angular (version 1) and facing an issue with my layout. I need to dynamically change the navigation based on the type of user that is logged in. To achieve this, I make an API request when the page loads to fetch the user object dat ...