JavaScript传递含File对象的数组至PHP的处理方法问询
解决FormData传递含File对象数组到PHP的问题
问题根源
JSON无法序列化浏览器的File对象,你把warranty.img = imgInput.files[0]放进对象再转成JSON字符串后,img字段会变成空对象或无意义的字符串,导致PHP里$data[0]['img']不是有效的文件索引,自然找不到$_FILES对应的键。
解决方案
不要将File对象混入JSON,而是通过FormData单独传递文件,同时把其他文本数据作为JSON字符串传递。
1. 修改JavaScript代码
移除对象中的img字段,单独将文件添加到FormData,命名规则和数组索引对应:
let warranty = {}; warranty.description = document.getElementById("txt_description").value; warranty.brand = document.getElementById("txt_marca").value; warranty.serie = document.getElementById("txt_serie").value; warranty.model = document.getElementById("txt_model").value; warranty.color = document.getElementById("txt_color").value; warranty.time_use = document.getElementById("txt_year_use").value; warranty.status = document.getElementById("dp_status").value; warranty.location = document.getElementById("dp_location").value; warranty.price = document.getElementById("txt_price").value; // 不要将File对象加入需要序列化的对象 warranties.push(warranty); let datos = new FormData(); datos.append("data", JSON.stringify(warranties)); // 单独添加文件,用索引区分(如果是多个条目,循环处理) datos.append("img_0", imgInput.files[0]);
如果是多个保修条目(多图),循环处理:
// 循环每个保修条目,移除img字段并单独添加文件 warranties.forEach((item, index) => { datos.append(`img_${index}`, item.img); delete item.img; }); datos.append("data", JSON.stringify(warranties));
2. PHP端处理代码
先解析文本数据,再通过对应的键获取$_FILES中的文件:
<?php // 解析文本数据 $data = json_decode($_POST["data"], true); // 处理单个图片 if (isset($_FILES['img_0'])) { $tmpPath = $_FILES['img_0']['tmp_name']; $fileName = $_FILES['img_0']['name']; $fileType = $_FILES['img_0']['type']; // 示例:将文件移动到上传目录(确保目录有写入权限) if (move_uploaded_file($tmpPath, './uploads/' . $fileName)) { echo "文件上传成功"; } else { echo "文件上传失败"; } } // 如果是多个图片,循环处理 foreach ($data as $index => $item) { $fileKey = "img_" . $index; if (isset($_FILES[$fileKey])) { // 处理逻辑同上 } } // 查看解析后的数据和文件信息 print_r($data); print_r($_FILES); ?>
内容的提问来源于stack exchange,提问作者juancho perez
相关产品推荐
相关产品推荐

