我正在尝试使用jquery和PHP上传多个文件。 但是我的表单数据没有按照PHP页面的要求提交。 请问有人可以帮我写出正确的文件上传方式吗?
以下是我的代码:
的index.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);
}
});
});
Controller.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)的输出: 阵列(0){ } 我在这里面临的问题是我发布的数据未在controller.php中被识别,并且控件未在if条件内到达。
答案 0 :(得分:1)
您需要将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)
答案 1 :(得分:1)
您的问题是,当它采用html表单时,您将jQuery对象作为参数传递给FormData构造函数
$('#upload_save').click(function(event){
event.preventDefault();
$.ajax({
url: 'controller.php',
type: 'post',
dataType: 'json',
data: new FormData(this.form), // pass the form itself to the constructor
processData: false,
contentType: false,
success: function(suc){
alert(suc['msg']);
},
error: function(error){
alert(error);
}
});
});