简体   繁体   中英

How to Save Image in mysql database using angular2 and php

I want to save image inside mysql database. How I can do that using php and angular??

Im using add-style.component.ts to upload image

imageUploadEvent(event){
    let imageFile = event.target;
    if(imageFile.files.length > 0){
      console.log(imageFile.files[0]);
      let formData = new FormData();
      formData.append('file',imageFile.files[0]);
      this._databaseService.insertImageData(formData).subscribe((msg) => {
        console.log(msg);
      },(error) =>{
        console.log("Get Some Error");
        console.log(error);
      });
    }
  }

I use add-style.html as following

<div class="container">
  <div class="row">
    <div class="col s8 offset-2">
      <div class="card-panel teal lighten-2">
        <h4>Image Uploading</h4>
      </div>
      <form #imageform ="ngForm">
        <input type="file" class="form-file-control" (change)="imageUploadEvent($event)"> 
        <button type="submit" class="btn-lg btn-submit form-control" (click)="saveFormData()" >submit</button>
      </form>
    </div>
  </div>
</div>

I use database.service.ts to call php

insertImageData(value){
    return this._http.get("http://localhost/jeleena-api/test-img.php",value).pipe(map(res => {
      console.log(res);
    }));
  }

Following is my php code

<?php

//Create Database Connection
include "db-connection.php";
if(!empty($_FILES['file'])){
    $ext = pathinfo($_FILES['file']['name'],PATHINFO_EXTENSION);
    $image = time().'.'.$ext;
    if(move_uploaded_file($_FILES["file"]["tmp_name"],$image)){
        $sql = "INSERT INTO test(img) VALUES('".$image."')";
        $conn->query($sql);
        echo "successfully uploaded";
    }
    else{
        echo ' error ';
    }

    }
?>

Ok bear with me. You can use ngStyle for this. https://angular.io/api/common/NgStyle You need to install the commonsmodule in your ngModule.

Now in your template you can do the following to show the image:

<div [ngStyle]="background-image: url('./assets/images/youImage.jpg');">

Now you are able to show your image based on a url. So what you can do is instead of saving the image to the sql just simple save the ./assets/images/youImage.jpg .

<div [ngStyle]="background-image: url(yourObject.image)>

And to show the image, you can make an object give it a property image and assign the string from the sql.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM