繁体   English   中英

使用Ajax上传文件

[英]Using Ajax to upload file

我已经尝试了几种变体(基于文章和其他SO论坛)以使其起作用,并且将其缩小为当我尝试将表单数据发送到PHP脚本时数据丢失的事实。 当我回显$ _FILES [“ file”] [“ name”]时,它为空。

我已经测试过,并且我的ajax和php脚本已连接,因为我可以返回一些数据,而不是任何表单数据。 显然,这导致文件未上传。

我当前的代码参考了这个论坛(lee8oi的答案): jQuery Ajax File Upload我开始了一个新论坛,因为这个问题是6年前提出的。

HTML:

<form id="signUpForm" name="signUpForm"  action="../functions/newUser.php" method="post">
    <input type="file" class="su_photo" name="file" id="user-photo">
    <input type="submit" id="sign-up" type="button" class="btn btn-primary btn-sm pull-right" value="Get Started">
</form>

js:

  $('#signUpForm').on('submit',function(){
        var fd = new FormData( $('#signUpForm') );
        fd.append("label", "WEBUPLOAD");
        $.ajax({
          url: "../../functions/newUser.php",
          type: "POST",
          data: fd,
          processData: false,  // tell jQuery not to process the data
          contentType: false   // tell jQuery not to set contentType
        }).done(function( data ) {
            console.log("PHP Output:");
            console.log( data );
        });
        return false;
    });

的PHP:

   if ($_POST["label"]) {
      $label = $_POST["label"];
    }
    $allowedExts = array("gif", "jpeg", "jpg", "png");
    $temp = explode(".", $_FILES["file"]["name"]);
    $extension = end($temp);
    if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/jpg")
    || ($_FILES["file"]["type"] == "image/pjpeg")
    || ($_FILES["file"]["type"] == "image/x-png")
    || ($_FILES["file"]["type"] == "image/png"))
    && ($_FILES["file"]["size"] < 200000)
    && in_array($extension, $allowedExts)) {
        if ($_FILES["file"]["error"] > 0) {
            echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
        } else {
            $filename = $label.$_FILES["file"]["name"];
            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("uploads/" . $filename)) {
                echo $filename . " already exists. ";
            } else {
                move_uploaded_file($_FILES["file"]["tmp_name"],
                "uploads/" . $filename);
                echo "Stored in: " . "uploads/" . $filename;
            }
        }
    } else {
        echo $_FILES["file"]["name"];
    }

我认为您只需要更改以下行

var fd = new FormData( $('#signUpForm') );

var fd = new FormData( $('#signUpForm')[0] );

要么

var fd = new FormData(this);

FormData的构造函数需要一个本机表单元素,而不是jQuery对象。 所以document.getElementById('signUpForm') $('#signUpForm')[0]this一切都能解决。

答案提供了进一步的解释。

暂无
暂无

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

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