我有一个包含两个文本字段和一个文件上传字段的表单。
验证完全由PHP处理,我使用一点Ajax来检索PHP脚本通过数组生成的错误消息(err [])。
我的问题是,我似乎无法让文件上传验证正常工作。 (上传文件时,总是会说“错误的文件格式只接受.png,.gif,.jpg,.jpeg”)
Ajax如下:
<?php
$submit=isset($_POST['done']);
if($submit)
{
$name=$_POST['name'];
$contact=$_POST['contact'];
$room=$_POST['mycheck'];
$totalCheckboxChecked = sizeof($_POST['mycheck']);
for($i=0;$i<$totalCheckboxChecked;$i++)
{
$roomchecked = $room[$i];
$db = new mysqli("localhost", "root", "","learndb");
$stmt=$db->prepare("INSERT INTO book_hotel (name,contact,booked_rooms) VALUES (?,?,?)");
$stmt->bind_param("sii",$name,$contact,$roomchecked);
$stmt->execute();
}
}
以下验证似乎总是被触发:
function checkform() {
$.post('upload.php', $("form#uploadForm").serialize(), function (data) {
$("div#error").html(data).slideDown("fast");
var destination = $('div#uploadContainer').offset().top - 15;
$("html:not(:animated),body:not(:animated)").animate({
scrollTop: destination
}, 200);
});
return false;
}
答案 0 :(得分:0)
if (isset($_FILES['uploadFile']) && $_FILES['uploadFile']['size'] != 0)
{
// Upload file
}
答案 1 :(得分:0)
$extension = end(explode('.', $_FILES['uploadFile']['name']));
if (!in_array($extension, $extensions))
{
$err[]='Wrong file format only .png , .gif, .jpg, .jpeg are accepted';
}
答案 2 :(得分:0)
由于$ extension的扩展名没有点(。)。从文件扩展名中删除点(。)
<div>{{getMyGlobal()}}</div>
将是
$extensions = array('.png', '.gif', '.jpg', '.jpeg','.PNG', '.GIF', '.JPG', '.JPEG');
希望这可以修复错误
答案 3 :(得分:0)
Per @ riddell的评论(AJAX File Upload with PHP Validation)
问题很可能不是php,而是Jquery本身。 这样的事情可以起作用
var form = $('form')[0];
var data = new FormData(form);
$.ajax({
url: 'upload.php',
data: data ,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
答案 4 :(得分:0)
更正上传和检查文件扩展名的逻辑
if (isset($_FILES['uploadFile']) && $_FILES['uploadFile']['size'] != 0)
{
$extension = end(explode('.', $_FILES['uploadFile']['name']));
if (!in_array($extension, $extensions))
{
$err[]='Wrong file format only .png , .gif, .jpg, .jpeg are accepted';
}
// Write code to upload image here
}
else
{
// There was error while uploading image
// $_FILES['uploadFile']['error'] gives error code
//
// Possible errors
// UPLOAD_ERR_OK: 0
// UPLOAD_ERR_INI_SIZE: 1
// UPLOAD_ERR_FORM_SIZE: 2
// UPLOAD_ERR_NO_TMP_DIR: 6
// UPLOAD_ERR_CANT_WRITE: 7
// UPLOAD_ERR_EXTENSION: 8
// UPLOAD_ERR_PARTIAL: 3
}