为了账号安全,请及时绑定邮箱和手机立即绑定

使用 Angular 6 php mysql 上传和检索图像

使用 Angular 6 php mysql 上传和检索图像

PHP
蛊毒传说 2022-01-14 18:12:37
我想通过 php 使用 angular 6 将图像上传到 mysql。之后,我想从数据库中检索图像以将其显示在 html 中。这是我的代码:export class Student {      idCard : string;      fname : string;      mname : string;      lname : string;      gender : string;      studentPhoto?: File; //what type of data should I use}用于显示照片 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 -->那么,我应该在角度和 MYSQL 中使用什么数据类型来存储图像?以及如何通过从 MYSQL 获取图像来显示图像?
查看完整描述

1 回答

?
犯罪嫌疑人X

TA贡献2080条经验 获得超4个赞

这是解决问题的完整实现:


在组件类中:


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);   

    });

  }    

}

在模板中:


<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">

学生服务:


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"];

      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");

 }


?>

获取图像.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表有两列:“ id ”和“ imagefile ”(类型 = LongBlob)


查看完整回答
反对 回复 2022-01-14
  • 1 回答
  • 0 关注
  • 119 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信