Abdulwehab
Abdulwehab

Reputation: 1428

uploading and retrieving image using angular 6 php mysql

I want to upload an image using angular 6 via php to mysql. After that, I want to retrieve the image from the database to display it in the html. Here is my code:

export class Student {

      idCard : string;
      fname : string;
      mname : string;
      lname : string;
      gender : string;
      studentPhoto?: File; //what type of data should I use
}

For displaying the photo student-details.component.html

<div class="col-xs-4">
  <img class="imageClass" src="student.studentPhoto" alt="Image not Recognized"/>
</div>
<!-- how can I set the src attribute -->

So, what data type should I use in the angular and also in the MYSQL to store the image? and How can I display the image by fetching it from MYSQL?

Upvotes: 0

Views: 2870

Answers (1)

Abdulwehab
Abdulwehab

Reputation: 1428

Here is the full implementation that solves the problem:

In the component class:

import { StudentService } from '../student-service.service';
import { DomSanitizer } from '@angular/platform-browser';

export class StudentRegistrationComponent implements OnInit {

 imageUrl = null;
 photo: Blob;

constructor(private _service: StudentService,
     public _DomSanitizationService: DomSanitizer) { }

setPhoto(event){
    this.photo = event.target.files[0];
  }
onClickSubmit(){
      const fd = new FormData();
      fd.append('stphoto',this.photo);
      this._service.postImage(fd).subscribe(res => console.log(res));
  }
showImage(){

    this._service.getImage().subscribe((res) => { 
      this.photo = res;
      var myReader:FileReader = new FileReader();
      myReader.onloadend = (e) => {
        this.imageUrl = this._DomSanitizationService.bypassSecurityTrustUrl(<string>myReader.result);
      }
      myReader.readAsDataURL(this.photo);   
    });
  }    
}

In the template:

<input id="photo" name="studentPhoto" type="file" (change)="setPhoto($event)" class="form-control">
<button class="btn btn-primary" (click) = "onClickSubmit()">submit</button>
<button (click)="showImage()">showImage</button>
<img [src]="imageUrl" height="200" width="200" class="img-thumnail">

StudentService:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class StudentService {

  constructor(private httpClient: HttpClient) { }

  postImage(fd : FormData): Observable<string>{
    return this.httpClient.post<string>('http://localhost:4000/files/postImage.php', fd );
  }

  getImage(): Observable<Blob> {
    return this.httpClient.get( 'http://localhost:4000/files/getImage.php', { responseType: 'blob' })      
 }
}

postImage.php

    <?php
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, DELETE, PUT');
    header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
    header('Access-Control-Allow-Credentials: true');
    $con = mysqli_connect("localhost:3306","root","","students");
    mysqli_set_charset($con, "utf8");
    
    if($_FILES["stphoto"])  
     {  
       $tmporary = $_FILES["stphoto"]["tmp_name"];
       $file_name = $_FILES["stphoto"]["name"];

        //don't forget to change 'ABDU' to your username.  

if(move_uploaded_file($tmporary,"C:\Users\ABDU\AppData\Local\_"."$file_name"))
            
        {
           
           if($file = addslashes(file_get_contents("C:\Users\ABDU\AppData\Local\_"."$file_name")))
           {
                $sql = "INSERT INTO imagedb (`imagefile`) VALUES ('$file')";
                mysqli_query($con,$sql);
                mysqli_query($con,"ALTER TABLE imagedb AUTO_INCREMENT = 1");
                echo json_encode("successfully injected");
           }
        }
    
           else
            echo json_encode("error");
     }
    
    ?>

getImage.php

<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, DELETE, PUT');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
header('Access-Control-Allow-Credentials: true');
$con = mysqli_connect("localhost:3306","root","","students");
mysqli_set_charset($con, "utf8");

$sql = "SELECT imagefile FROM imagedb";
$result = mysqli_query($con,$sql))

$row = mysqli_fetch_assoc($result);
echo $row['imagefile'];

?>

imagedb table has two columns: 'id' and 'imagefile' (type = LongBlob)

Upvotes: 2

Related Questions