PHP使用onchange将文件上传到Ajax [英] PHP upload file to Ajax using onchange
问题描述
function chkFile(file1) {
var file = file1.files[0];
var formData = new FormData();
formData.append('formData', file);
$.ajax({
type: "POST",
url: "chkFileType.php",
contentType: false,
processData: false,
data: formData,
success: function (data) {
alert(data);
}
});
}
<form action="" method="post" name="myForm" id="myForm" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
Upload Files
<input type="file" name="uploadFile" id="uploadFile" onChange="chkFile(this)"/>
<input type="submit" name="submitbutt" value="Checkout">
chkFileType.php
chkFileType.php
<?php
print_r($_FILE)
?>
我想创建一个表单,当用户上传文件时,它会检查在提交整个表单之前上传文件。上传文件时我使用 onChange
然后将 formData
值传递给Ajax以调用我的 chkFileType.php
进行检查并提醒响应。
I want to create a form that when the user uploads a file, it will do a check on the uploaded file before submitting the whole form. I use onChange
when a file is uploaded and then pass the formData
value to Ajax to call my chkFileType.php
to do the checks and alert back the response.
该函数正在运行,没有任何错误,但 alert(data)没有响应
;
The function is running without any errors, but no response from alert(data)
;
我知道我做错了什么,但不知道从哪个方向走。我做得对吗?
I know I am doing something wrong, but have no idea which direction to go from. Am I doing the right way?
推荐答案
一切都很好看。你做得对了。但要从ajax调用获得任何响应,您必须在 chkFileType.php
中打印所需的内容。
Everything looks fine. You have done in right way. But to get any response from an ajax call, you have to print the required stuff in chkFileType.php
.
比如,
if($ext =="jpg" || $ext == "png"){
echo "Image"; // data in alert will alert as Image
} else if(check for txt file){
echo "Text File"; // data in alert will alert as Text File
} else if(chck for pdf) {
echo "Pdf";// data in alert will alert as Pdf
}
编辑
更改此
var formData = new FormData( $("#formID")[0] );
希望你理解我的意思。
这篇关于PHP使用onchange将文件上传到Ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!