简体   繁体   English

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)
?>

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. 我在上传文件时使用onChange ,然后将formData值传递给Ajax,调用我的chkFileType.php进行检查并提醒响应。

The function is running without any errors, but no response from alert(data) ; 该函数正在运行,没有任何错误,但没有来自alert(data)响应;

I know I am doing something wrong, but have no idea which direction to go from. 我知道我做错了什么,但不知道从哪个方向走。 Am I doing the right way? 我做得对吗?

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 . 但要从ajax调用获得任何响应,您必须在chkFileType.php打印所需的内容。

Like, 喜欢,

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  
}

EDIT change this 编辑改变了这一点

var formData = new FormData( $("#formID")[0] );

Hope you understand what i meant to say. 希望你明白我的意思。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM