我正在尝试发布我通过ajax上传的文件。使用简单帖子时,我的文件上传和验证无需javascript即可运行。但是当打开javascript并且表单必须通过ajax提交时,它不起作用。我相信我通过ajax处理文件上传的方式存在问题,但我无法弄清问题是什么。
JQuery(这里是ajax):
var first_name = $('#first-name').val();
var last_name = $('#last-name').val();
var school = $('#school-register').val();
var formData = new FormData('#transcript');
var url="post.php";
$.ajax({
type: 'POST',
url: url,
data: {first_name: first_name,last_name: last_name,school:school,file:formData}
})
.done(function(response_data)
{
alert(response_data);
});
return false;
HTML表单:
<form id="animate1" enctype="multipart/form-data" method="post" action="post.php">
<input id="first-name" name="first_name" type="text" value="" placeholder="First Name" maxlength="100">
<input id="last-name" name="last_name" type="text" value="" placeholder="Last Name" maxlength="100">
<input id="school-register" name="school" type="text" value="" placeholder="High School" maxlength="100">
<label for="transcript">Transcript</label><input type="file" id="transcript" name="file">
PHP:
if ((isset($_POST['first_name'])) && (strlen(trim($_POST['first_name'])) > 0))
{
$first_name = stripslashes(strip_tags($_POST['first_name']));
}
else
{
$msg = "Student's first name required!";
$_SESSION['msg'] = $msg;
$url = "noJS.php";
header("Location: $url");
exit;
}
同样的姓氏和学校名称。
文件的PHP:
if (isset($_FILES['file']) && $_FILES['file']['error'] == UPLOAD_ERR_OK)
{
$fInfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($fInfo,$_FILES['file']['tmp_name']);
$attach = false;
switch($mime)
{
case 'application/pdf':
$attach = true;
break;
default:
$msg = "Wrong file format of transcript (please upload a PDF file)!";
$_SESSION['msg'] = $msg;
$url = "noJS.php";
header("Location: $url");
exit;
}
$mail->AddAttachment($_FILES['file']['tmp_name'],
$_FILES['file']['name']);
}