我有一个简单的部分,用户可以在其中上传文件,现在我想在文件成功上传后显示成功消息
HTML
<form id="uploadform" action="upload.php" method="post" enctype="multipart/form-data">
<label for="file"><span>Filename:</span></label>
<input type="file" id="fileupload" name="file" id="file" />
<br />
<input id="#submit_cf" type="submit" name="submit" class="btn btn-primary" value="Upload file" />
</form>
<span id="success_message"></span>
Ajax ;
function doSuccess(acton,message,disable)
{
$(acton).show();
$(acton+' h2').text(message);
$(disable).attr('disabled','disabled');
}
$('#uploadform').on('submit',function(e){
// This is fine, it does prevent the form from submitting
e.preventDefault();
var form_data = $('#fileupload').prop('files')[0];
console.log(form_data);
// Run messaging
doSuccess('#success_message','Processing, please wait...','#submit_cf');
// Run ajax
$.ajax({
url : "upload.php",
type: "POST",
data: form_data,
success: function(response) {
$('#success_message ').text(response);
}
});
});
在控制台console.log(form_data);
返回这个
这里是upload.php
<?php
$allowedExts = array("jpg", "jpeg", "gif", "png", "mp3", "mp4", "wma");
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if ((($_FILES["file"]["type"] == "video/mp4")
|| ($_FILES["file"]["type"] == "audio/mp3")
|| ($_FILES["file"]["type"] == "audio/wma")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg"))
&& ($_FILES["file"]["size"] < 5000000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
现在,当我上传文件时,出现以下错误
jquery.min.js:4 Uncaught TypeError: Illegal invocation
我的代码有什么问题吗?
最佳答案
您正在将一个文件传递给data
,并且 jQuery 在尝试将其编码为表单数据时出错。
你应该:
- 改为传递真实的表单数据对象
- 告诉 jQuery 不要处理数据
- 告诉 jQuery 不要设置 Content-Type(浏览器将使用 FormData 对象自动执行此操作)
因此:
var form = $('#uploadform')[0];
var form_data = new FormData(form);
$.ajax({
url : "upload.php",
type: "POST",
data: form_data,
processData: false,
contentType: false,
success: function(response) {
$('#success_message ').text(response);
}
});
关于javascript - PHP 和 Ajax : Illegal invocation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57571407/