Is it possible to combine file and form data into a single API request in Angular 4 when uploading?

admin.component.ts

admin.component.html

Here is a snippet of the code used for uploading form data. Although I am able to post the form data to the API, I am facing difficulties with uploading the file.

admin.component.ts

private onFileChange(event: any) {
// let reader = new FileReader();
console.log("in file change method");
if (event.target.files && event.target.files.length > 0) {
  this.file = event.target.files[0];
  console.log(event.target.files);

   }

}

private onSubmit(userform: any) {
    let _formData= new FormData();
    console.log(userform.value);
    userform.value.IdpMetadataFile = this.file;
    console.log(userform.IdpMetadataFile)
    console.log('formData', userform.value);
    this._adminServices.saveAdminConfig(userform.value).subscribe(response => {
  console.log(response);
  this.saveAdmin = true;
});
console.log("save admin " + this.saveAdmin);

}

....admin.component.html...

<div class="form-group">
        <p>Browse IDP Metadata file</p>
        <input type="file" name="IdpMetadataFile " id="IdpMetadataFile " (change)="onFileChange($event)" [(ngModel)]="ViewAdminConfigData.IdpMetadataFile "
            #idpMetaFileName="ngModel">
        <br>

Answer №1

In order to add the file to the formdata object, you will need to use the `append` method.

submitForm(){
   let formData = new FormData();
   formData.append('file', this.selectedFile);
   // make an API call to send the formData
}

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

Finding key and value in a select with Ant Design

How can I search for both a user's display name (e.g. "John Smith") and username (e.g. "johsmi") in a user object? In the following example, only usernames are searched while display names are not: <Select showSearch={true} optionFilterProp=" ...

Eliminate list items with a keyboard stroke

I am currently developing a straightforward todo list application using JavaScript. The main functionality I am trying to implement is the ability to add new items from an input field to a list, as well as the option to remove items from the list. While ...

Unable to Trigger Virtual Click Event on Calendar in JavaScript

My workplace utilizes a custom web application with a date picker/calendar that I am attempting to modify programmatically. The app is built in Vue, which has added complexity to my task. Despite exhaustive efforts, I have been unable to select or inject d ...

What could be causing the issue with multiple selection in jQuery?

I am interested in implementing multiple selection on my ASP page. I came across the pickList jQuery plugin and followed the instructions provided at the following link: Below is a snippet from my ASP page: <%@ Page Language="C#" AutoEventWireup="true ...

Can you explain the distinction between $.param and JSON.Stringify?

I am encountering an issue with my code snippet: $http({ url: config.apiUrl + 'mail/Sendmail', method: 'POST', data: JSON.stringify({ Body: $scope.Message, ...

What is the correct way to utilize the createAsyncThunk function in TypeScript?

You can access the entire project here. I currently have this code snippet: extraReducers: (builder) => { builder .addCase(getTodosAsync.fulfilled, (state, action:any) => { return action.payload.todos ...

What is the best way to capture the inputs' values and store them accurately in my object within localStorage?

Is there a more efficient way to get all the input values ​​and place them in the appropriate location in my object (localStorage) without having to individually retrieve them as shown in the code below? Below is the function I currently use to update ...

Change the class of a button in React by toggling state without causing the component to re-render

I'm facing an issue with changing the class of a button in react js when clicked using hooks. The problem arises when the class toggles due to a state change, as the initial class is rendered instead of the toggled one. Any assistance would be greatly ...

I am interested in using AngularJS to redirect to a different page

I am looking to navigate to another page within the application, similar to how it is done in MVC or asp.net applications. Below is the Route.js file that I have defined. The route.js file is structured as follows: var MainApp=angular.module('Routin ...

What is the solution to toggling the openAll() or closeAll() functionality for an Angular Material expansion panel button?

Is there a way for me to toggle between two buttons: OpenAll and CloseAll? Can I determine the state of mat-accordion, whether it is fully opened or closed, using a boolean value? <div class="row"> <mat-icon *ngIf="accordion.op ...

The Journey of React Components: How Child Components Embrace the State Props of the Past

My understanding of states and props in React seems to be off. I am working on a React, Redux based app. Situation: I have a global SVG component that grabs the viewport dimensions from the app in the componentDidMount method. The default props for the ...

Mastering the art of redirection in Node.js

Encountering an issue with redirecting between directories - having trouble directing to another file in a different directory. Here is my directory structure: -views -add_user.jade -routes -index.js Attempting to redirect to add_user.jade from inde ...

Adapting setInterval Timer in Angular Using a Range Slider

Currently, I am working with Ionic 4 and Angular. In my project, I aim to incorporate the Ionic range slider. This useful feature allows users to adjust a range of values by simply moving a slider. However, I encountered an issue regarding the refresh rate ...

What is the best way to connect CodeIgniter with Angular.js?

Are you facing challenges while integrating Angular.js and CodeIgniter? In my main.js, I'm utilizing ngRoute to define routes as follows: $locationProvider.html5Mode(true); $routeProvider.when('/test', { templateUrl: 'partials/te ...

Access a designated tab using cbpFWTabs

I am currently using the cbpFWTabs plugin from Tympanus for my tabs (http://tympanus.net/Development/TabStylesInspiration/). However, I am struggling to open a specific tab upon page load. I have attempted to create a show method within the page script, bu ...

Having success in FF and Chrome, but encountering issues in IE? What could be causing this disparity

My partner wrote a script, but he is currently offline so I am trying to troubleshoot the issue on my own. Here is the current code we are working with: function checkProgress(Progress) { // Retrieve progress status $.get('http://www.site.c ...

The modification of HTML styles

How can I change the style (width, color etc) of all 8 functions like this? function my(){document.getElementById("question1").innerHTML="THIS QUESTION"+ "<br>" +"<button onclick=answer1() id=ques1 >first answer</button>" +"<button ...

A guide on extracting and converting strings in React to display as HTML

I am in the process of developing a simple blog app using a MERN stack. Currently, I have the functionality to create posts with just plain text. Is there a way to incorporate HTML rendering within the content of these posts? For example, a post might con ...

JavaScript code that triggers when a checkbox is not selected

I'm attempting to dynamically add an input field when a checkbox is clicked, with the intention of having the checkbox already checked by default. However, I am encountering an issue where the checkbox remains unchecked even after the input field is d ...

Issue encountered with sortable table in list.js

Encountering a puzzling error while implementing list.js and tabletop for a sortable table sourced from a Google Doc. The error message reads: "Uncaught TypeError: Cannot read property 'childNodes' of undefined," pinpointing the first line in lis ...