AngularPHP

Upload Image In Angular With PHP

In this post, we will learn how to upload file and save as Base64 into the folder using PHP API. To convert image into Base64 we will use Angular and For API we will use PHP.

There are many ways to upload image in Angular but in this post we will upload and convert file in Base64 and then save it into the folder using PHP.

Below are the steps to upload image in Angular and web services in PHP. So let’s follow following steps to do this.

Step 1 Create Angular Project.

Create angular app using below command.

ng new imageupload

Step 2 Import Module.

In this step we need to import HttpClientModule to app.module.ts. So open app.module.ts file and and import it.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule, ReactiveFormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
   
import { AppComponent } from './app.component';
   
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 3 Update Component File.

Add below code in app.component.ts file.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
imageSrc:any = '';
status:boolean = false
constructor(private http: HttpClient) { }
ngOnInit(): void { }
onFileChange(event:any) {
this.status = false
const file = event.target.files[0];
this.status = event.target.files.length>0?true:false
if(this.status==true){
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
this.imageSrc = reader.result;
}
}
}
submit(){
this.http.post('http://localhost/phpapi/imageupload.php', {'image':this.imageSrc})
.subscribe(res => {
console.log(res);
alert('Uploaded Successfully.');
})
}
}
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { imageSrc:any = ''; status:boolean = false constructor(private http: HttpClient) { } ngOnInit(): void { } onFileChange(event:any) { this.status = false const file = event.target.files[0]; this.status = event.target.files.length>0?true:false if(this.status==true){ const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => { this.imageSrc = reader.result; } } } submit(){ this.http.post('http://localhost/phpapi/imageupload.php', {'image':this.imageSrc}) .subscribe(res => { console.log(res); alert('Uploaded Successfully.'); }) } }
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http'; 

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  imageSrc:any = '';
  status:boolean = false

  constructor(private http: HttpClient) { }

  ngOnInit(): void { }

  onFileChange(event:any) {
    this.status = false
    const file = event.target.files[0];
    this.status = event.target.files.length>0?true:false
    if(this.status==true){
       const reader = new FileReader();
       reader.readAsDataURL(file);
       reader.onload = () => {
          this.imageSrc = reader.result;          
       }
    }

  }

  submit(){

    this.http.post('http://localhost/phpapi/imageupload.php', {'image':this.imageSrc})
      .subscribe(res => {
        console.log(res);
        alert('Uploaded Successfully.');
      })
  }

}

Step 4 Update HTML File.

Add below code in app.component.html file.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<h6 class="text-primary" align="center">Image Upload With Angular And PHP</h6>
<label for="file">Select Image</label>
<input (change)="onFileChange($event)" id="file" type="file">
<button [disabled]="!status"class="btn btn-primary" type="submit" (click)="submit()">Upload</button>
<h6 class="text-primary" align="center">Image Upload With Angular And PHP</h6> <label for="file">Select Image</label> <input (change)="onFileChange($event)" id="file" type="file"> <button [disabled]="!status"class="btn btn-primary" type="submit" (click)="submit()">Upload</button>
<h6 class="text-primary" align="center">Image Upload With Angular And PHP</h6>
    <label for="file">Select Image</label>
      <input  (change)="onFileChange($event)"  id="file" type="file">         
  <button [disabled]="!status"class="btn btn-primary" type="submit" (click)="submit()">Upload</button>

Step 5 : Create API in PHP.

Add below code imageupload.php

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
$folderPath = "upload/";
$postdata = file_get_contents("php://input");
if(!empty($postdata)){
$request = json_decode($postdata);
$image_parts = explode(";base64,", $request->image);
$image_type_aux = explode("image/", $image_parts[0]);
$image_base64 = base64_decode($image_parts[1]);
$file = $folderPath . uniqid() . '.png';
if(file_put_contents($file, $image_base64)){
$response[] = array('sts'=>true,'msg'=>'Successfully uploaded');
}
echo json_encode($response);
}
?>
<?php header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Methods: PUT, GET, POST"); header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept"); $folderPath = "upload/"; $postdata = file_get_contents("php://input"); if(!empty($postdata)){ $request = json_decode($postdata); $image_parts = explode(";base64,", $request->image); $image_type_aux = explode("image/", $image_parts[0]); $image_base64 = base64_decode($image_parts[1]); $file = $folderPath . uniqid() . '.png'; if(file_put_contents($file, $image_base64)){ $response[] = array('sts'=>true,'msg'=>'Successfully uploaded'); } echo json_encode($response); } ?>
<?php     
   header("Access-Control-Allow-Origin: *");
   header("Access-Control-Allow-Methods: PUT, GET, POST");
   header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
   
    $folderPath = "upload/";
    $postdata = file_get_contents("php://input");	 
    if(!empty($postdata)){
    $request = json_decode($postdata);
    $image_parts = explode(";base64,", $request->image);      
    $image_type_aux = explode("image/", $image_parts[0]); 
    $image_base64 = base64_decode($image_parts[1]);      
    $file = $folderPath . uniqid() . '.png';      
    if(file_put_contents($file, $image_base64)){	
	$response[] = array('sts'=>true,'msg'=>'Successfully uploaded');
    }      
     echo json_encode($response);
   }
?>

Now our API and UI are ready, so run both application and check it.

Reactive Form Validation In Angular. Multi Step Form In Angular.

Related Articles

Leave a Reply

Check Also
Close
Back to top button