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

如何通过ajax将图片上传至服务器目录 配合现有PHP接口存储数据

实现方案

一、前端修改

方案1:基于原有jQuery Ajax调整

要传递文件需要使用FormData对象承载所有请求参数,代码如下:

// 获取选中的文件
const fileInput = document.getElementById('myFileInput');
const selectedFile = fileInput.files[0];

// 构造FormData对象
const formData = new FormData();
// 原有普通字段
formData.append('name', person.name);
formData.append('age', person.age);
formData.append('height', person.height);
formData.append('weight', person.weight);
// 追加文件
if (selectedFile) {
  formData.append('avatar', selectedFile);
}

$.ajax({
  method: "POST",
  url: "https://www.example.com/main/public/actions.php",
  data: formData,
  // 必须加这两个配置,否则jQuery会错误处理FormData
  processData: false,
  contentType: false,
  success: function (response) {
    console.log(response)
  }
})

方案2:现代Fetch API实现(更推荐)

Fetch是原生JS标准API,无需依赖jQuery,代码更简洁:

const fileInput = document.getElementById('myFileInput');
const selectedFile = fileInput.files[0];
const formData = new FormData();

formData.append('name', person.name);
formData.append('age', person.age);
formData.append('height', person.height);
formData.append('weight', person.weight);
if (selectedFile) {
  formData.append('avatar', selectedFile);
}

fetch('https://www.example.com/main/public/actions.php', {
  method: 'POST',
  body: formData
})
.then(res => res.text())
.then(data => console.log(data))
.catch(err => console.error('请求出错:', err));

*注意:使用Fetch时不需要手动设置Content-Type请求头,浏览器会自动生成带边界标识的multipart/form-data头。

二、服务端PHP修改

前置准备

  1. 先给persons表新增存储图片路径的字段,例如执行SQL:ALTER TABLE persons ADD COLUMN avatar varchar(255) DEFAULT NULL;
  2. 确保images目录有Web服务进程的写入权限,可执行chmod 755 images调整权限。

修改后的actions.php代码

<?php
include "config.php";

if(isset($_REQUEST["name"])) {
    $name = $_REQUEST["name"];
    $age = $_REQUEST["age"];
    $height = $_REQUEST["height"];
    $weight = $_REQUEST["weight"];
    $avatarPath = null;

    // 处理文件上传
    if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] === UPLOAD_ERR_OK) {
        $allowExt = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        $fileInfo = pathinfo($_FILES['avatar']['name']);
        $ext = strtolower($fileInfo['extension']);
        // 校验文件格式,防止恶意文件上传
        if (!in_array($ext, $allowExt)) {
            echo "不允许的文件格式,仅支持图片上传";
            exit;
        }
        // 生成唯一文件名避免覆盖
        $fileName = uniqid() . '.' . $ext;
        $targetPath = __DIR__ . '/images/' . $fileName;
        // 移动文件到目标目录
        if (move_uploaded_file($_FILES['avatar']['tmp_name'], $targetPath)) {
            $avatarPath = $fileName;
        }
    }

    // 修复原代码SQL注入漏洞,使用预处理语句
    $stmt = $conn->prepare("INSERT INTO persons (name, age, height, weight, avatar) VALUES (?, ?, ?, ?, ?)");
    $stmt->bind_param("sddds", $name, $age, $height, $weight, $avatarPath);

    if ($stmt->execute()) {
        echo "New person stored successfully !";
        exit;
    } else {
        echo "Error: " . $stmt->error;
        exit;
    }
}
?>

*注意:原代码直接拼接SQL参数存在严重SQL注入风险,上述代码已替换为mysqli预处理语句,是目前PHP操作数据库的安全标准写法。

内容的提问来源于stack exchange,提问作者Vaggelis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 00:27:05