Is it feasible to send FormData and an Image file together to a web API from an Angular 6 application?

Is it feasible to send both form data and an image file to a web API from an Angular 6 application?

app.component.ts

onSelectFile(event) {
  if (event.target.files && event.target.files[0]) {
    this.imageToUpload = event.target.files[0];
    const reader = new FileReader();
    reader.onload = e => this.selectedImage = reader.result.toString();
    this.fileName = event.target.files[0].name;
    reader.readAsDataURL(this.imageToUpload);
  }
}

createNewComitteeMember() {
  var mServiceObject = {
    ComitteeMemberName: this.comittee_Member_Name.value,
    ComitteeMemberNumber: this.comittee_Member_Number.value,
    ComitteeMemberType: this.comittee_Type.value,
    ComitteeMemberTypeOthers: this.comittee_Type_Others.value,

    ComitteeMemberPosition: this.comittee_Member_Position.value,
    ComitteeMemberPositionOthers: this.comittee_Member_Position_Others.value,
    ComitteeMemberStatus: this.comittee_Member_Status.value
  }

  this.dmlService.CreateNewComitteeMember(mServiceObject, this.imageToUpload ).subscribe(data => {
    console.log(data);

  });
}

service.ts

CreateNewComitteeMember(mFormData,mImage){
// How can I combine the mFormData and mImage here and pass them to the web API?
}

Could someone assist me in resolving this issue.

Answer №1

If you're looking to handle data submissions, FormData is the way to go.

HandleFormDataSubmission(formData, image){
  const uploadOptions = {
    headers: new HttpHeaders({ "Content-Type": "multipart/form-data"})
  }
  const newData = new FormData();
  newData.append('data', formData);
  newData.append('image', image);
  return this.httpClient.post(url, newData, uploadOptions)
}

To learn more about FormData, visit the link provided.

Answer №2

If you want to combine two objects into a single object, one way to achieve this is by using the following method:

mergeObjects(dataObject1, dataObject2) {
   dataObject1['key'] = dataObject2;
}

The challenge with your approach lies in the fact that HTTP imposes restrictions on the amount of data that can be POSTed. To circumvent this limitation, you can specify the Content-Type Header as 'multipart/form-data'. While this may require multiple server trips for transferring all the data, combining the information before sending it might not be necessary. However, if required,

Answer №3

One way to handle file uploads is by utilizing FormData

backend implementation:

uploadFile(selectedFile: File) {
        let httpHeaders = new HttpHeaders();
        let options = {
            headers: httpHeaders
        };
        const formData = new FormData();
        formData.append('File', selectedFile, selectedFile.name);
        return this.httpClient.post('api/upload', formData, options);
    }

frontend component:

onFileSelect(event) {
       if (event.target.files && event.target.files[0]) {
           this.selectedImage = event.target.files[0];
           this.fileService.uploadFile(this.selectedImage)
      }
  }

Answer №4

If you're looking for a solution, give this method a shot - it did the trick for me!

const formData = new FormData();
formData.append("userData", this.userInput.value);
formData.append("image", this.uploadedImage.value);

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

The default route in Angular2 RC5 is set to display the AppComponent

My Angular2 application starts with an AppComponent that contains the main navigation bar and router outlet for the rest of the app. By convention, this is considered the starting point of the application. I also have a routes component that currently doe ...

Issues arise when building with Angular using `ng build`, but everything runs smoothly when using `

My Angular 5 application uses angular-cli 1.6.8 { "name": "test", "version": "0.0.0", "license": "MIT", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "karma": "ng test", "test": "jest", "test:watch": "j ...

Encountering an issue with Angular 18 and SignalR while compiling the application: [ERROR] Unable to resolve "url", "https", "http", "util" from eventsource

Looking to implement real-time technology in an Angular 18 application? SignalR is the chosen technology, but encountering issues during the package setup and build process. The error might be linked to the build process, potentially due to Angular moving ...

JavaScript library experiencing import issues with Typescript custom type

Working on a Vue project with TypeScript, I encountered an issue when importing a custom type created for the vue-numeral-filter package. The error message received is as follows: ERROR in /Users/bmartins/Development/app-invest/src/main.ts(14,30): 14:30 ...

How can I rename an event function in Angular 2?

Is it possible to dynamically change the function associated with an event? I attempted to do so like this: (click) = "{{myFunction}}" However, I encountered an error stating "Parser Error: Got interpolation ({{}}) where expression was expected". I am lo ...

(firebase-admin) Issue: Why is the client showing as offline when it's actually online?

import * as admin from "firebase-admin"; import DataModel from "../types/firebase"; export class FirebaseManager { db = admin.database(); constructor() { this.db = admin.database(); if (this.db === undefined) { throw ...

"Unlocking the treasure trove: Extracting a single item from my Firebase real-time database using

Searching for the user's article in my Realtime database to display information. https://i.sstatic.net/yCdgf.png This is my Ionic script page Below are the imports I have: I am able to retrieve the user's ID, but I'm facing difficulty in ...

A guide to adding images to dropdown options in Angular 6

I'm having trouble getting an icon or image to appear next to text in a dropdown menu. I'm currently working with Angular 6 and despite trying multiple solutions, I haven't been able to make it work. All I want is to display a flag next to ...

Contrasting expressEngine and ng2engine: An In-depth Comparison

I am currently utilizing the universal-starter framework. In regards to the file server.ts, I noticed that making the switch from import { expressEngine } from 'angular2-universal'; app.engine('.html', expressEngine); to import { n ...

Is there a way to conceal the progress output of an Angular build during test execution using Karma?

Currently, I am setting up a build process for an Angular 4 application and aiming to prevent progress output in order to keep the runner's logs clean. The project configurations were automatically created using angular cli (v1.0.1) By utilizing ng ...

How to install a library from a Github repository in Angular 2

Currently, I am in the process of learning how to develop an Angular 2 library based on a project that has been built with Angular-CLI. To aid me in this endeavor, I am referencing the examples set by Nikita Smolenskii in ng-demo-lib and ng-demo-app. With ...

What is the most effective way to share data among components in React?

I recently delved into learning about react and find myself puzzled on how to pass data between two components. Presently, I have set up 2 functions in the following manner: First, there's topbar.tsx which displays information for the top bar, inclu ...

Execute automated tests using Selenium on an Angular web application using headless Chrome

I am currently working on developing Selenium tests for an Angular application. My objective is to have these tests integrated into my continuous integration builds, requiring them to be executed in headless mode using Chrome. So far, I have created two s ...

Frequent occurrence when a variable is utilized prior to being assigned

I am currently working with a module import pino, { Logger } from 'pino'; let logger: Logger; if (process.env.NODE_ENV === 'production') { const dest = pino.extreme(); logger = pino(dest); } if (process.env.NODE_ENV === &apo ...

Typescript input event

I need help implementing an on change event when a file is selected from an input(file) element. What I want is for the event to set a textbox to display the name of the selected file. Unfortunately, I haven't been able to find a clear example or figu ...

How can I adjust the appearance of an HTML tag within an Angular component?

I have created an Angular component with the following definition: import { Component, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'rdc-dynamic-icon-button', templateUrl: './dynamic-icon-button. ...

Is there a way to retrieve the anticipated DOM structure prior to the initialization of the view?

Consider this component: @Component({ selector: "form-control", template: ` <div class="form-group" #div> <label [for]="inputId">{{label}}</label> <ng-content></ng-content> <small [id]="helpId" cl ...

Utilize Regular Expression Constant Validator in Angular 8's Reactive Formbuilder for efficient data validation requirements

Is there a way to efficiently store and reuse a Regex Validator pattern in Angular while following the DRY principle? I have a reactive formbuilder with a Regex validator pattern for ZipCode that I need to apply to multiple address forms. I'm interes ...

What should I do about typescript and ES6?

An error occurred while running my code: [0] app/components/people/details/PersonDetailComponent.ts(27,35): error TS2339: Property 'person' is missing from type '{}'. Here is the code snippet in question: export class PersonDeta ...

What is the best way to bring a string into my .tsx file using a relative reference from a module?

I am currently developing an online course on creating a website using StencilJS, NodeJS, and the IonicFramwork. As a newcomer in this field, I have encountered a challenging issue: In my project, the API "https://swapi.dev/api" is imported as a ...