You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中如何将表单数据与图片文件上传至PhpMyAdmin的books表?

Angular中如何将表单数据与图片文件上传至PhpMyAdmin的books表?

嘿,刚上手Angular很正常,我帮你梳理下代码里的问题,再补上对应的PHP后端代码,这样就能把数据存到books表里啦!


一、先修正你的Angular代码问题

1. 模板文件(apublish.component.html)的错误

你把formControlName拼写成formController了,每个输入框都要改过来,另外我还修正了重复的placeholder文本:

<div class="container-fluid">
  <div class="row">
    <div class="md-col-12 text-center bg-warning">
      <h1>Image </h1>
    </div>
  </div>
  <div class="container">
    <form [formGroup]="form" (ngSubmit)="onSubmit()">
      <div class="form-group input-group-lg">
        <input class="form-control" placeholder="Book name" formControlName="bname">
      </div>
      <div class="form-group">
        <input type="file" (change)="uploadFile($event)">
      </div>
      <div class="form-group input-group-lg">
        <input class="form-control" placeholder="Book author" formControlName="bauthor">
      </div>
      <div class="form-group input-group-lg">
        <input class="form-control" placeholder="Book genre" formControlName="bgenre">
      </div>
      <div class="form-group input-group-lg">
        <input class="form-control" placeholder="Book summary" formControlName="bsummary">
      </div>
      <div class="form-group">
        <button class="btn btn-success btn-block btn-lg btn-block">Submit</button>
      </div>
    </form>
  </div>
</div>

2. 组件文件(apublish.component.ts)的错误

  • 模板绑定的是onSubmit(),但你定义的方法是submitImage(),得统一成onSubmit()
  • uploadFile里给表单赋值时字段名写错,应该是bpic而非image
  • 响应处理的逻辑有重复判断,修正后代码如下:
import { HttpEvent, HttpEventType, HttpResponse } from '@angular/common/http';
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { ImageUploadService } from './image-upload.service';

@Component({
  selector: 'app-apublish',
  templateUrl: './apublish.component.html',
  styleUrls: ['./apublish.component.css']
})
export class ApublishComponent {
  title="ngFileUpload";
  form:FormGroup;
  progress:number=0;
  msgs: any;
  imgMsg: any;

  constructor(public fb: FormBuilder, public imageUploadService: ImageUploadService){
    this.form=this.fb.group({
      bname:[''],
      bpic:[null],
      bauthor:[''],
      bgenre:[''],
      bsummary:['']
    })
  }

  uploadFile(event:any){
    const file=event.target.files ? event.target.files[0] :'';
    this.form.patchValue({
      bpic:file // 修正字段名,对应表单定义的bpic
    });
    this.form.get('bpic')?.updateValueAndValidity()
  }

  // 统一方法名,和模板的ngSubmit绑定对应
  onSubmit(){
    this.imageUploadService.imageUpload(
      this.form.value.bname,
      this.form.value.bpic,
      this.form.value.bauthor,
      this.form.value.bgenre,
      this.form.value.bsummary
    ).subscribe((event:HttpEvent<any>)=>{
      switch (event.type){
        case HttpEventType.UploadProgress:
          if(event.total){
            this.progress=Math.round((100/event.total)*event.loaded);
            this.msgs=`Uploaded! ${this.progress}%`; // 修正模板字符串写法
          }
          break;
        case HttpEventType.Response:
          if(event.body.success){
            this.imgMsg=event.body.success;
          } else {
            this.imgMsg=event.body.error;
          }
          setTimeout(()=>{
            this.progress=0;
            this.msgs='';
          },1500);
      }
    })
  }
}

3. 服务文件(image-upload.service.ts)

这里逻辑没问题,只需注意PHP端接收的文件字段是filetoUpload,后面PHP代码会对应处理。


二、编写PHP后端代码(single-upload.php)

这是你需要的PHP脚本,它会接收Angular传来的FormData,处理图片上传并插入数据到books表:

<?php
// 1. 数据库连接配置
$servername = "localhost";
$username = "你的数据库用户名"; // 例如root
$password = "你的数据库密码";
$dbname = "你的数据库名";

// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

// 2. 处理文件上传
$targetDir = "uploads/"; // 需在PHP脚本同级目录创建uploads文件夹,并设置可写权限
$fileName = basename($_FILES["filetoUpload"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);

// 允许的图片格式
$allowedTypes = array('jpg','png','jpeg','gif');
$uploadOk = 1;

if(!in_array($fileType, $allowedTypes)){
    $response = array("success" => false, "error" => "只允许JPG, JPEG, PNG & GIF格式的图片");
    echo json_encode($response);
    exit;
}

// 尝试上传文件
if(move_uploaded_file($_FILES["filetoUpload"]["tmp_name"], $targetFilePath)){
    // 3. 插入数据到books表
    $bname = mysqli_real_escape_string($conn, $_POST['bname']);
    $bauthor = mysqli_real_escape_string($conn, $_POST['bauthor']);
    $bgenre = mysqli_real_escape_string($conn, $_POST['bgenre']);
    $bsummary = mysqli_real_escape_string($conn, $_POST['bsummary']);
    $bpic = $targetFilePath; // 存储图片的相对路径

    $sql = "INSERT INTO books (bname, bpic, bauthor, bgenre, bsummary) VALUES ('$bname', '$bpic', '$bauthor', '$bgenre', '$bsummary')";

    if ($conn->query($sql) === TRUE) {
        $response = array("success" => true, "success" => "书籍信息上传成功");
        echo json_encode($response);
    } else {
        $response = array("success" => false, "error" => "插入数据库失败: " . $conn->error);
        echo json_encode($response);
    }
} else {
    $response = array("success" => false, "error" => "图片上传失败,请检查uploads文件夹权限");
    echo json_encode($response);
}

$conn->close();
?>

三、注意事项

  • 务必在PHP脚本同级目录创建uploads文件夹,并设置可写权限(Linux下可执行chmod 755 uploads)
  • 替换PHP代码中的数据库用户名、密码和数据库名,确保能正常连接到你的PhpMyAdmin数据库
  • 若要提升安全性,建议使用预处理语句替代直接拼接SQL,避免SQL注入风险

备注:内容来源于stack exchange,提问作者Darshana Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.23 08:19:31