Angular 13: How to Handle an Empty FormData Object When Uploading Multiple Images

I attempted to upload multiple images using "angular 13", but I'm unable to retrieve the uploaded file in the payload. The formData appears empty in the console.

Any suggestions on how to resolve this issue?

Here is the HTML code:

 <form [formGroup]="myForm" (ngSubmit)="submit()">
    <div class="form-group">
        <label for="file">File</label>
        <input id="file" type="file" multiple class="form-control" (change)="onFileChange($event)">
        <div *ngIf="f.file.touched && f.file.invalid" class="alert alert-danger">
            <div *ngIf="f.file.errors && f.file.errors.required">File is required.</div>
        </div>
    </div>
    <button class="btn btn-primary" type="submit">Submit</button>
</form>    

gallery.ts

   onFileChange(event: any) {
    if (event.target.files.length > 0) {
      for (var i = 0; i < (event.target.files.length); i++) {
        this.myFiles.push(event.target.files[i]);
        this.myForm.get('file')?.setValue(this.myFiles);
        console.log('my files check', this.myFiles);
      }
    }
  }   


submit() {
let id = localStorage.getItem('uid');
const formData = new FormData();
for (var i = 0; i < this.myFiles.length; i++) {
  formData.append("file[]", this.myFiles[i]);
}
let payload = {
  'url': '/api/uploadgallery',
  'formData': formData,
  'id': id,
}
console.log('form data check', payload);
this.playerService.postFilegallery(payload).subscribe((response: any) => {
  console.log('resonsecheck', response);
});    

Service.ts

    postFilegallery(sendData: any) {
    console.log('send data check',sendData);
    let headers = {
      'Accept': 'multipart/form-data'     
    };
    return this.http.post(API_URL + sendData.url, sendData, { headers: headers })
      .pipe(map(res => {
        res
        alert('Uploaded Successfully.');
      }));
  }    

Answer №1

I can't pinpoint the reason why the formData property is blank, but it seems like you have incorrectly assigned the multipart/form-data value to the header. Instead of using 'Accept': 'multipart/form-data', try switching it to

'Content-Type': 'multipart/form-data'

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

Operators within an observable that perform actions after a specific duration has elapsed

Is there a way in an rxjs observable chain to perform a task with access to the current value of the observable after a specific time interval has elapsed? I'm essentially looking for a functionality akin to the tap operator, but one that triggers onl ...

Analysis of cumulative revenue using Palantir Foundry Function

I am in need of creating a function that can transform raw data into target data. The raw data consists of a table with columns for customer, product, and revenue, while the target data includes customer, revenue, and cumulative revenue. customer produ ...

Issues arise when Angular properties become undefined following the initialization or OnInit functions

There seems to be a peculiar issue with the properties of an angular component that I have set up. It appears that these properties are losing their values after the initialization process. The component is essentially a basic HTML file containing a video ...

Setting up Tarui app to access configuration data

I am looking to save a Tauri app's user configuration in an external file. The TypeScript front end accomplishes this by: import {appConfigDir} from "tauri-apps/api/path"; ... await fetch(`${await appConfigDir()}symbol-sets.json`) { ... ...

The property 'item' is not found within the specified type 'IntrinsicAttributes & RefAttributes<Component<{}, any, any>>'. Error code: 2322

"react": "^16.12.0", "typescript": "^4.0.3", "next": "^9.4.4" The error being raised by typescript is related to the <Item item={item} key={item.id} urlReferer={urlReferer} /> prop used ...

Changing the generic type's constraint type in TypeScript to have more flexibility

I have developed a utility type named DataType that takes in a parameter T restricted to the type keyof MyObject. When the key exists in MyObject, DataType will return the property type from MyObject; otherwise, it will simply return T. interface MyObject ...

Break apart the string and transform each element in the array into a number or string using a more specific type inference

I am currently working on a function that has the ability to split a string using a specified separator and then convert the values in the resulting array to either strings or numbers based on the value of the convertTo property. Even when I call this fun ...

Substitute all attributes of objects with a different designation

I need to update all object properties from label to text. Given: [ { "value": "45a8", "label": "45A8", "children": [ { "value": "45a8.ba08", "label": "BA08", &q ...

Before accessing the page, please ensure to make a double request

Encountered a weird issue, While inspecting the network tab in Chrome devtools, I noticed that my Vue app is making double requests to the same endpoint :/ Here's a snippet of my code: In the router section, I have a beforeEach function. When I navig ...

Storing data locally in Angular applications within the client-side environment

As I delve into Angular and TypeScript, I've encountered a perplexing issue. Let's say I have two classes - Employee and Department. On the server-side, I've established a Many-To-One relationship between these entities using Sequelize: db. ...

react-navigation hook for navigating

Currently, I am utilizing the react-navigation hook and instead of repeating the hook in various components, my goal is to pass navigation as a prop. const navigation = useNavigation(); ... <MyButton resetLocation={resetLocation} navigation= ...

Steps to enable the submit button in angular

Here's the code snippet: SampleComponent.html <nz-radio-group formControlName="radiostatus" [(ngModel)]="radioValue" (ngModelChange)="onChangeStatus($event)"> <label nz-radio nzValue="passed">Passed</label> <label nz-rad ...

You cannot invoke this expression while destructuring an array of React hooks in TypeScript

Within my React TypeScript component, I have several fields that check a specific condition. If the condition is not met, the corresponding field error is set to true in order to be reflected in the component's DOM and prevent submission. However, whe ...

Achieving TypeScript strictNullChecks compatibility with vanilla JavaScript functions that return undefined

In JavaScript, when an error occurs idiomatic JS code returns undefined. I converted this code to TypeScript and encountered a problem. function multiply(foo: number | undefined){ if (typeof foo !== "number"){ return; }; return 5 * foo; } ...

Ensuring the accuracy of nested objects through class validator in combination with nestjs

I'm currently facing an issue with validating nested objects using class-validator and NestJS. I attempted to follow this thread, where I utilized the @Type decorator from class-transform but unfortunately, it did not work as expected. Here is my setu ...

What is the best way to refresh a personalized form element using Angular?

I have developed a custom form control with validation that utilizes a standalone FormControl to manage the value and perform certain validations. Is there a method in Angular to reset the inner FormControl when the control is being reset from another For ...

Blending ASP.NET Core 2.0 Razor with Angular 4 for a Dynamic Web Experience

I am currently running an application on ASP.NET Core 2.0 with the Razor Engine (.cshtml) and I am interested in integrating Angular 4 to improve data binding from AJAX calls, moving away from traditional jQuery methods. What are the necessary steps I need ...

Building a filter for a union type in TypeScript: a step-by-step guide

Allow me to present an example to demonstrate my current objective. const v1: { type: "S"; payload: string } = { type: "S", payload: "test" }; const v2: { type: "N"; payload: number } = { type: "N", payload: 123 }; type Actions = typeof v1 | typeof v2; ...

Which option is more beneficial for intercepting API data in Angular 6: interfaces or classes?

My API returns JSON data that is not structured the way I need it, so I have to make changes. { "@odata.context":"xxxxxx", "id":"xxxxxxxx", "businessPhones":[ ], "displayName":"name", "givenName":"pseudo", "jobTitle":null, "ma ...

Exploring Angular 2 Tabs: Navigating Through Child Components

Recently, I've been experimenting with trying to access the HTML elements within tabs components using an example from the Angular 2 docs. You can view the example here. Here is a snippet of my implementation: import {Component, ElementRef, Inj ...