javascript - 无法使用 ajax 和 php 上传多个文件
问题描述
我正在尝试使用 jquery 和 PHP 上传多个文件。但是我的表单数据没有按照 PHP 页面的要求提交。拜托,有人可以帮我写出正确的上传文件方式吗?
下面是我的代码:
索引.php:
<form id="step17Form" action="" name="step17Form" method="post" enctype="multipart/form-data">
<div style="text-align :left; margin-left:15px"> <label><big>
(<span style="color: red; font-family: Comic Sans MS;"><small style="font-weight: bold;">Note: Max File Size - 75KB</small></span>)</big></label>
<br><br>
<table style="text-align: centre; width: 800px; margin-left:15px" border="0" id="upload" cellpadding="6" cellspacing="6">
<tbody>
<tr>
<td><br><label for="stuphoto"><span style="font-family: Comic Sans MS;">1. Student Photo</label></span>
</td>
<td><br><input id="file-upload" name="stuphoto" type="file" accept=".JPG" class="custom-file-upload" style="display: inline;"></td>
</tr>
<tr>
<td><br><label for="stuadhar"><span style="font-family: Comic Sans MS;">2. Aadhar Card</label></span>
</td>
<td><br><input name="stuadhar" accept=".jpg,.pdf" class="custom-file-upload" type="file" style="display: inline;"></td>
</tr>
</tbody>
</table>
</div>
<br>
<input type="hidden" name="reason" value="step17" />
<button type="submit" id="upload_save" class="btn btn-success"> Save And Next >></button>
</form>
JS:
$('#upload_save').click(function(){
event.preventDefault();
$.ajax({
url: 'controller.php',
type: 'post',
dataType: 'json',
data: new FormData($(this).parents('form')),
processData: false,
contentType: false,
success: function(suc){
alert(suc['msg']);
},
error: function(error){
alert(error);
}
});
});
控制器.php:
$reason = $_POST['reason'];
var_dump($_FILES);
if ($reason === "step17" ) {
var_dump($_FILES);
$status=array();
$uploaded_file=array();
$document_type=array("Photo","Aadhar");
$i=0;
$j=0;
foreach($_FILES as $key=>$file)
{
$status= uploadImage($key, $file_size=5000000, "../..".FILE_PATH_LOC );
if($status['error']!==200 && $status['status']===false )
{
echo json_encode(array('status'=>'false','msg'=>"Error ".$file['name']." ".$status['msg']));
break;
}
}
}
var_dump($_FILES): array(0){ } 的输出 我在这里面临的问题是我发布的数据在 controller.php 中没有被识别,并且控制没有到达 if 条件内。
解决方案
您需要将 stuphoto 作为数组。或者请尝试更改此行
<td><br><input id="file-upload" name="stuphoto" type="file" accept=".JPG" class="custom-file-upload" style="display: inline;"></td>
至
<td><br><input id="file-upload" name="stuphoto[]" type="file" accept=".JPG" class="custom-file-upload" style="display: inline;"></td>
和
foreach($_FILES as $key=>$file)
至
foreach($_FILES['stuphoto']['name'] as $key=>$file)
推荐阅读
- angularjs - PhpStorm 抱怨找不到类型,但仍然可以打开定义它的文件
- onedrive - 使用一个驱动器一键列出文件和文件夹
- php - 按外键mysql同一张表排序
- c - 指针变量的地址是如何分配的?他们遵循任何模式吗?
- javascript - 使用 php、已验证域、mx、电子邮件模式检查电子邮件是否存在
- reactjs - Redux 状态未定义
- docker - 多阶段 docker 构建的工件缓存
- c# - 尝试将 enum system.array 转换为 enum List
在c#中 - javascript - FullCalendar Json 字符串引号属性
- apache-kafka - kafka ksql 提取 json 字段文字美元符号