我有一个html表单,我有输入文件数组。我试图实现的是通过它获取php文件循环中的文件数组并检查文件扩展名是否正确,否则将其添加到数组,然后在ajax中显示为json数组。有人能帮我吗?这是表格的代码:
<html>
<head>
<title>Multiple file upload handling</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#form").submit(function(e){
var file1 = $("#file1").val();
var file2 = $("#file2").val();
$("#results").text("");
var results = $("#results");
if(file1 == "" || file2 == ""){
results.text("File 1 and File 2 are empty.");
}else {
var formarray = new FormData($("#form")[0]);
$.ajax({
url: "upload.php",
type: "POST",
dataType: "JSON",
enctype: 'multipart/form-data',
async: false,
cache: false,
contentType: false,
processData: false,
data: formarray,
success:function(response){
if(response.success == false){
$(response.message).each(function(index, value){
results.append("<li id="+ index + ">" + value + "</li>");
});
}else{
alert(response.message);
}
}
});
}
e.preventDefault();
});
})
</script>
</head>
<body>
<form method="post" role="form" enctype="multipart/form-data" id="form">
<input type="file" id="file1" name="file[]" style="margin-bottom:30px;"><br>
<input type="file" id="file2" name="file[]" style="margin-bottom:30px;"><br>
<input type="submit" id="upload" name="upload">
</form>
<div id="results"></div>
</body>
</html>
以下是php代码:
<?php
$filenames = $_FILES['file']['name'];
$filesizes = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
$data = array();
$errors = array();
foreach($filenames as $key=>$value){
$filesize = $_FILES["file"]["size"][$key];
$filetype = $_FILES["file"]["type"][$key];
$file_tmpname = $_FILES["file"]["tmp_name"][$key];
$valid_extensions = array("jpeg", "jpg", "gif", "png");
$ext = explode(".", $value);
$extension = end($ext);
if(!in_array($extension, $valid_extensions)){
$errors[] = $value;
$data["success"] = false;
$data["message"] = $errors;
} else {
$data["success"] = true;
$data["message"] = "success";
move_uploaded_file($file_tmpname, "uploads/".$filename);
}
}
echo json_encode($data);
?>