Having trouble uploading an image using Angular, encountering an error in the process

Whenever I try to upload an image, the server keeps throwing an error saying

Cannot read property 'buffer' of undefined
. I am using Node.js as a backend server and interestingly, when I send the image through Postman, it gets stored in MongoDB without any issues.

Despite reading multiple posts on Stack Overflow, I still can't figure out what's causing this error. It seems like I'm missing something crucial here.

// HTML Code

<label for="InputImage">Upload Image</label>
<input type="file" accept="image/*" title="image" 
(change)="handleImageInput($event)"
 class="form-control" id="InputImage">

// Component.ts

imageToUpload: File;

handleImageInput($event) {
this.imageToUpload = $event.target.files[0];
}

addPackage() {
const obj = this.onSubmit();
const dataToSend = {
  ...obj,
  title: this.packageForm.controls.title.value,
  price: this.packageForm.controls.price.value,
};

const formData = new FormData();
formData.append('Image',this.imageToUpload,this.imageToUpload.name);

this.submitted = true;
if (this.packageForm.valid) {
  this.submitting = true;
  this.submitText = 'Submitting';
  this.packageService.addPackage(dataToSend,formData).subscribe(res => {
    this.data = res;
    if (this.data.status == true) {
      this.toasterService.showSuccess('Package added Successfully');
      this.reset();
    }
  }, error => {
    console.log(error);
  }, () => {
    this.submitting = false;
    this.submitText = 'Submit';
  }
  );
} else {
  this.toasterService.showFailure('Please fill all the fields');
}
}

// Service.ts

addPackage(packageData: IProduct,imageData) {
console.log(packageData);
return this.http.post(this.apiUrl + 'spectrum/package/addPackage', 
{
  title: packageData.title,
  productNames: packageData.productNames,
  productQuantities: packageData.productQuantities,
  price: packageData.price
},imageData)
}

Answer №1

Properly constructing the image data using the FormData object is key, however sending it through the third parameter of the HttpClient is not recommended. The third parameter should be the 'options' argument, not the body. When utilizing FormData for data transmission, all data should be sent exclusively through the FormData object. Additionally, on the server side, ensure that the endpoint specifies that the request content-type is 'multipart/data-form'; do not mix 'application/json' and 'multipart/data-form' on the same endpoint. It's best practice to use only one type of data format.

Answer №2

To enhance the functionality, consider incorporating headers into your code like so:

addNewPackage(data: IProduct, imageData) {
    let headers = new Headers();
    headers.append('Content-Type', 'multipart/form-data');
    headers.append('Accept', 'application/json');
    
    let options = new RequestOptions({ headers: headers });
    console.log(data);
    
    return this.http.post(this.apiUrl + 'spectrum/package/addPackage', 
    {
        title: data.title,
        productNames: data.productNames,
        productQuantities: data.productQuantities,
        price: data.price
    }, imageData, options)
}

I hope you find this helpful.

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

Using RxJs in an Angular 2 application to enable row selection in a table by detecting mouse movements

Check out this example of an Angular 2 application with row selection in a table: https://plnkr.co/edit/HdQnWqbg9HloWb4eYGHz. The row selection functionality is implemented using mouse event handlers (mousedown, mousemove, mouseup). Below is the template ...

Next.js displays an error when attempting to update the `AuthContextProvider` component while rendering the `Login` component

I have developed a basic next.js application that involves user login functionality through a graphql-api. The login process utilizes the react context-API to update the context once the user successfully logs in. Upon successful login, the intention is to ...

Encountering an error from the Angular CLI compiler can be frustrating, but fear not! By making a simple change (that can always

When I was compiling my app for the first time using ng serve I encountered this error: img error However, when I made a change to one of the comp files (it could be any file), and webpack recompiled it with Angular CLI - everything worked fine. I sus ...

Differences between Angular2 local template variables and Jade ID shortcutsIn Angular2, local

Angular2 has introduced the local template variable feature, which is created using #var. When using the Jade Template Engine, this syntax gets converted to #var="var". Is there a method to avoid this conversion? Otherwise, accessing the original local t ...

The <mat-radio-button> component does not have a value accessor specified

When working with HTML and Angular, I encountered the following issue: <mat-radio-group> <mat-radio-button [(ngModel)]="searchType"> And (Narrower search) </mat-radio-button> <mat-radio-button [(ngModel)]="searchType"&g ...

Getting Data Beyond the .subscribe() in AngularFire 2

Currently, I have a piece of code that retrieves user data from a database. import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; import {AngularFireAuth} from 'angularfire2/auth'; import { ...

Encountering error TS2304: Cannot resolve name 'classes' when attempting to apply styling in React using Typescript

I'm having trouble customizing the styles on my website, specifically when trying to add a custom className. Error Message: Cannot find name 'classes'. TS2304 Below is the code I am currently working with: import React from 'react& ...

Leveraging the power of NextJs and the googleapis Patch function to seamlessly relocate files and folders to a specific

I am currently working on a functionality to move specific files or folders to another folder using nextjs + googleapis. Here is the code I have been testing: const moveFileOrFolder = async () => { if (!session || !selectedItemId || !destinationFolder ...

Uploading files using Angular 6 to communicate with a Flask (Python) API

I have developed a web service using Flask to save files, following the example provided in the official Flask documentation: @app.route('/parse_table', methods=['POST']) def upload_file(): print(request.files) # check if the p ...

React: Retrieved information, yet unable to access the properties of the object

After successfully fetching data from an API call and seeing the results in console, I am facing issues with accessing object properties and displaying them. interface Data { data: [] isLoading: boolean } function About() { const [ dataUser, ...

Angular: Dynamically Displaying Components based on Conditions

I have a unique component design: <div class="custom-component__section {{ style }}"> <header class="custom-component__header"> <ng-content *ngIf="!displayHeader" select="[custom-header]">< ...

Determining the type of a single deconstructed variable from an object

My useForm hook is designed to take an object and return several useful functions back, including that object as a state. However, due to TypeScript limitations, the specific type from the initial object cannot be returned because useForm accepts dynamic o ...

How do you properly perform typechecking on a custom fetch function in ReactQuery? I'm encountering an error that states: "....is of an unknown type."

Currently, I am working with typescript + react-query and creating a custom fetch function. I am struggling to properly type this function and encountering a TypeScript error when attempting to use myQuery.error.message const locationQuery: QueryObserverRe ...

Guide to incorporating dynamic components into Angular Router

I am currently working on developing a pluggable Angular application. During my research, I came across the following insightful article: Building an extensible Dynamic Pluggable Enterprise Application with Angular Everything was going smoothly until I ...

Typescript encounters difficulty locating the designated interface

Within my Aurelia View-Model, I am working on a Typescript file that contains the following structure: import {Chart} from './chart'; interface IMargin { top: number, right: number, bottom: number, left: number } export class App{ cha ...

How can I ensure I am receiving real-time updates from a Resolver Service by subscribing and staying in sync with the

How can I effectively implement this code without encountering an error? "Property 'resolve' in type 'DocumentaryResolverService' is not assignable to the same property in base type 'Resolve'." import { Documentary } from ...

Error NG8001: The element 'router-outlet' is not recognized: Make sure that 'router-outlet' is a component in Angular, and confirm that it is included in this module

Having trouble running ng serve or ng build due to an error message stating that 'router-outlet' is not a recognized element. The Angular application structure looks like this: app.module.ts: import { NgModule } from '@angular/core'; i ...

Error: Unable to access 'match' property of an undefined value

After upgrading my Angular application from version 12 to 13, I encountered an error during unit testing. Chrome Headless 94.0.4606.61 (Windows 10) AppComponent should create the app FAILED TypeError: Cannot read properties of undefined (reading &a ...

Tips on skipping the need to repeatedly use `@ApiProperty()` for every dto in NestJs-swagger

I'm currently exploring ways to streamline the process of specifying @ApiProperty() for each DTO. I've heard about a method involving the creation of a nest-cli.json file, where if you define Promise<DTO> in your controller within nest-swa ...

Struggling to access the "this.array" variable within a TypeScript-powered Angular 4 application

I cannot access the this.array variable in my TypeScript-Angular 4 application. The error is being thrown at this.services.push because this.services is undefined. My code looks like this: export class ServersComponent implements OnInit { //Initializi ...