Uploading images using Angular and PHP: A comprehensive guide

I am a beginner in Angular and I am having trouble uploading an image from Angular as I encounter 4 errors:

1) Error in the post method: Cannot find name 'formData'. Did you mean 'FormData'?ts(2552)
2) Error in the subscribe method: const headers: HttpHeaders
No overload matches this call.
Overload 1 of 5,
3) Error in the subscribe method:Cannot find name 'file'. Did you mean 'File'?ts(2552)
4) Error in this.url: Type 'string | ArrayBuffer' is not assignable to type
'string'.
Type 'ArrayBuffer' is not assignable to type 'string'

Below, I have provided the code snippet.

public imagePath;
constructor(private http: HttpClient) { }
url: string;
ngOnInit() {
}
onSelectFile(event) 
{ // called each time file input changes
if (event.target.files && event.target.files[0]) 
{
    var reader = new FileReader();
    this.imagePath = event.target.files;

    for (const file of this.imagePath) 
    {
      const formData = new FormData();
      formData.append('image', file, file.name);
    }
    const headers = new HttpHeaders();
    headers.append('Content-Type', 'multipart/form-data');
    headers.append('Accept', 'application/json');

    this.http.post('http://localhost/imageupload.php', formData).subscribe( headers, console.log(file.name) );

    reader.readAsDataURL(event.target.files[0]); // read file as data url

    reader.onload = (event) => { // called once readAsDataURL is completed
    this.url = event.target.result;

    }
}
}

Answer №1

Constants are block-scoped, meaning you do not have access to a constant from an outer scope (for is also block-scoped).

let imagePath;
constructor(private http: HttpClient) { }
url: string;

ngOnInit() {
}

onSelectFile(event) { // called each time file input changes
  if (event.target.files && event.target.files[0]) {
    var reader = new FileReader();
    imagePath = event.target.files;
    
    for (const file of imagePath) {
      const formData = new FormData();
      formData.append('image', file, file.name);
      
      const headers = new HttpHeaders();
      headers.append('Content-Type', 'multipart/form-data');
      headers.append('Accept', 'application/json');
      
      this.http.post('http://localhost/imageupload.php', formData, { headers }).subscribe(response => console.log(response));
      
      reader.readAsDataURL(event.target.files[0]); // read file as data url
      
      reader.onload = (event) => { // called once readAsDataURL is completed
        this.url = event.target.result;
      }
    }
  }
}

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

M.E.A.N - Suite for setting up and defining backend boundaries consisting of MongoDB, Express.js, Angular2, node.js

Seeking knowledge on how the frameworks and platforms Angular 2 and Express.js collaborate in the 'mean' approach is my main query. I am interested in understanding where the client-side ends and the server-side begins. After delving into this t ...

Incorrect Date Range Picker Alignment

I am having trouble with the positioning of a mat date-range-picker calendar inside a component. I have a menu component that calls another component called leave, which contains the mat date range picker calendar. The problem is that when I call the leav ...

Rendering an Angular page with data using Node.js

I have a scenario for my website where users need to input a URL with a parameter (an ID) and receive back the corresponding page containing information from the database. I am using Angular4 but I am unsure of how to achieve this. It's straightforwa ...

What is the best way to identify the main dark color in Angular Material, and what other color variables are available for use with Angular Material?

Hey there, I'm trying to figure out how to utilize the primary dark color from angular material. I attempted using color="p-dark" but it doesn't seem to be working. Any ideas on how to access the dark color defined by the material color tool? I w ...

Why does the Material button style take time to apply when my Angular application first loads instead of being immediate?

Inside the Angular application I'm working on, there is a toolbar component that consists of three different links. The first link directs to the main app page, while the other two lead to distinct components within the app. Each link is styled with c ...

Methods of obtaining the array size using interpolation in Angular2?

Is there a way to inquire about the size of an array in Angular 2 when it is used within a component? For instance, consider the following: users : User[]; where export class User { id : number; firstName : String; lastName : String; userName ...

A comprehensive guide on constructing a literal object in Typescript by combining an array with an object

Recently, I came across this Typescript code snippet: type SortedList = T[] & {_brand: "sorted" }; function binarySearch<T>(xs: SortedList<T>, x: T): boolean let low = 0; let high = xs.length - 1; while (high ...

Unusual conduct exhibited by a 16th version Angular module?

I've created a unique component using Angular 16. It's responsible for displaying a red div with a message inside. import { ChangeDetectionStrategy, Component, Input, OnInit, } from "@angular/core"; import { MaintenanceMessage } ...

Generating a dynamic table using Angular

My goal is to populate a table dynamically using the code below: teams.component.ts import { Component, OnInit } from '@angular/core'; import { first } from 'rxjs/operators'; import { TeamService } from 'src/app/services/team.ser ...

Button activated by specified row index in Angular test

I've been working on testing the enabling or disabling of a button based on the selected rowIndex in Angular 11. However, I'm facing an issue where the test expects component.deleteRoleButtonDisabled to be false but it always evaluates to true. D ...

Error: The function $.cookie() is not defined in Angular2 Typescript

After installing @types/jquery, I updated tsconfig.json to include jquery.cookie in the types section. Visual Studio Code indicates that $.cookie is ready for use, but when I execute my code, an error appears in the console stating that $.cookie() is not ...

Angular 2+ seems to be failing to detect and update changes in variables within the template

I have a component that includes rendering the user's name from the profile object. The corresponding part of the template looks like this: <button mat-button [matMenuTriggerFor]="userMenu" *ngIf="isAuthenticated()"> {{profile?.name} ...

Transforming JSON data into comma-delimited values (with thousands separators) using Angular 5 and ES6 syntax

Is there a more elegant method to convert a JSON response into comma-separated numbers for displaying currency purposes? Here is the code I have currently: let data = { "business":{ "trasactionTableData":[ { ...

Using `this` within an object declaration

I am encountering an issue with the following code snippet: const myObj = { reply(text: string, options?: Bot.SendMessageOptions) { return bot.sendMessage(msg.chat.id, text, { reply_to_message_id: msg.message_id, ...options }) ...

Transform a standard array of strings into a union string literal in TypeScript

I'm currently developing a module where users can specify a list of "allowable types" to be utilized in other functions. However, I'm encountering challenges implementing this feature effectively with TypeScript: function initializeModule<T ex ...

Easy steps for importing node modules in TypeScript

I'm currently navigating the world of TypeScript and attempting to incorporate a module that is imported from a node module. I have chosen not to utilize webpack or any other build tools in order to maintain simplicity and clarity. Here is the struct ...

Having trouble with VSCode/tsconfig path configurations, as the files are being fetched but still receiving a "Module not found" error in the editor

Since I began working on this project, I've been encountering a peculiar issue. When importing modules and files in my Angular components/classes using import, I face an error in VSCode when the paths use the base path symbol @. Strangely enough, desp ...

Execute a function when a button is pressed in a React application

Currently, I am dynamically generating some HTML and have a requirement for certain "events" to trigger an onclick function. The technology stack I am using for this project involves React and TypeScript. My initial approach is as follows: function add_ev ...

Encountering errors while running Angular 8's ng build prod command

After successfully migrating my project from Angular 7 to Angular 8, I encountered an issue when attempting to run 'ng build prod' which resulted in the following error: ERROR in Error during template compile of 'Ng2CompleterModule' Cou ...

Zero-length in Nightmare.js screenshot buffer: an eerie sight

I'm currently working on a nightmare.js script that aims to capture screenshots of multiple elements on a given web page. The initial element is successfully captured, but any subsequent elements below the visible viewport are being captured with a l ...