AJAX文件上传给出了未定义的文件错误

时间:2017-02-03 20:16:51

标签: javascript php jquery ajax upload

首先让我解释一下我的目标,然后显示我的代码。

我想要做的是创建一个基本上更新用户在数据库中的详细信息的页面,我首先完成了这一部分,并且通过AJAX完成所有工作。接下来我想通过AJAX更新用户的个人资料图片,所以我创建了一个普通的文件上传PHP页面,以确保我的PHP代码工作正常,确实如此。现在我只需要通过AJAX执行上传,这就是我遇到的问题。我不断收到来自PHP页面的错误消息,其中指出undefined index: file

请随时提出任何问题,并感谢您的回复。

这是我的HTML表单:

<form action="upload.php?upload&type=profile" method="post" enctype="multipart/form-data">
    <label for="profile">Profile Picture</label><br />
    <img id="preview" width="200" height="200" src="<?php echo $user->getProfile(); ?>" alt="Profile Picture Preview" /><br />
    <br />
    <input type="file" name="file" id="file" onchange="loadImage(this);" /><br />
    <label for="username">Username</label><br />
    <input type="text" name="username" id="username" value="<?php echo $user->getUsername(); ?>" /><br />
    <label for="email">Email Adress</label><br />
    <input type="text" name="email" id="email" value="<?php echo $user->getEmail(); ?>" /><br />
    <label for="bio">Biography</label><br />
    <textarea name="bio" id="bio" cols="40" rows="5"><?php echo $user->getBio(); ?></textarea><br />
    <label for="password">New Password</label><br />
    <input type="password" name="password" id="password" /><br />
    <label for="oldPass">Current Password</label><br />
    <input type="password" name="oldPass" id="oldPass" /><br />
    <label for="first">First Name</label><br />
    <input type="text" name="first" id="first" value="<?php echo $user->getFirstName(); ?>" /><br />
    <label for="last">Last Name</label><br />
    <input type="text" name="last" id="last" value="<?php echo $user->getLastName(); ?>" /><br />
    <br />
    <input type="submit" name="update" value="Save" id="update" />&nbsp;<input type="button" name="reset" value="Reset Fields" onclick="resetFields()" />
</form>

这是我的包含AJAX的js文件:

$(document).ready(function() {
    $("#update").click(function() {
        profile = "pictures/default.jpg";
        username = $("#username").val();
        email = $("#email").val();
        bio = $("#bio").val();
        newPass = $("#password").val();
        oldPass = $("#oldPass").val();
        first = $("#first").val();
        last = $("#last").val();

        // First an ajax request to upload the image as it requires separate request
        $.ajax({
            type: "POST",
            url: "upload.php?upload&type=profile",
            data: new FormData(this),
            contentType: false,
            cache: false,
            processData: false,
            success: function(resp) {
                alert(resp);
            },
            error: function (resp) {
                alert(resp);
            }
        });

        // Now the updates in the profile
        $.ajax({
            type: "POST",
            url: "update.php",
            data: "mode=details&profile="+profile+"+&username="+username+"&email="+email+"&bio="+bio+"&password="+newPass+"&oldPass="+oldPass+"&first="+first+"&last="+last,
            success: function(resp) {
                // resp contains what is echoed on update.php
                alert(resp);
            }
        });
        return false;
    });
});

最后,这是我的PHP代码:

include "base.php";
// Kick user off this page if they are not logged in
if (!isset($user)) {
    echo "<meta http-equiv='refresh' content='0.1;url=index.php'>";
    exit();
}
if (isset($_GET['upload'])) {
    switch ($_GET['type']) {
        case "profile": {
            $dir = "pictures/";
            $maxFileSize = 2000000; // 2mb
            $extensions = array("jpg", "jpeg", "png", "gif");
            $currentPath = pathinfo($_FILES['file']['name']);
            $fileType = $currentPath['extension'];
            $targetFile = $dir.$user->getUsername()."Profile.".$fileType;
        }
        break;
        default: {
            echo "<meta http-equiv='refresh' content='0.1;url=index.php'>";
            exit();
        }
        break;
    }

    $upload = true;

    // Check the file size
    if ($_FILES['file']['size'] > $maxFileSize) {
        echo "The file is too large.";
        $upload = false;
    }

    // Limit file types
    if (!in_array($fileType, $extensions)) {
        echo "This file type is not allowed.";
        $upload = false;
    }

    // Check if file upload is allowed and upload if it is
    if ($upload) {
        if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFile)) {
            echo basename($_FILES['file']['name']);
        } else {
            echo "There was an error during file upload.";
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您的代码存在一些问题。对于一个,因为您的按钮位于Form内并且您只关联该按钮上的click,那么该表单正在提交正常且非常混乱的jquery。为了在jquery中正确捕获表单,您需要将其作为submit运行,并添加e.preventDefault();,以便运行ajax中的代码而不是在页面上提交的实际表单。

您需要添加e.preventDefault();,这样您的表单才会提交,因为您有form个标记。也从click更改为submit

$("form").submit(function(e) {
    e.preventDefault();
    profile = "pictures/default.jpg";
    username = $("#username").val();
    email = $("#email").val();
    bio = $("#bio").val();
    newPass = $("#password").val();
    oldPass = $("#oldPass").val();
    first = $("#first").val();
    last = $("#last").val();

    // First an ajax request to upload the image as it requires separate request
    $.ajax({
        type: "POST",
        url: "upload.php?upload&type=profile",
        data: new FormData(this),
        contentType: false,
        cache: false,
        processData: false,
        success: function(resp) {
            alert(resp);
        },
        error: function (resp) {
            alert(resp);
        }
    });

    // Now the updates in the profile
    $.ajax({
        type: "POST",
        url: "update.php",
        data: "mode=details&profile="+profile+"+&username="+username+"&email="+email+"&bio="+bio+"&password="+newPass+"&oldPass="+oldPass+"&first="+first+"&last="+last,
        success: function(resp) {
            // resp contains what is echoed on update.php
            alert(resp);
        }
    });
    return false;
});

如果您正在处理页面上的多个表单,或者动态创建表单,那么您将需要使用

$(document).on('submit', 'form', function(e) {
...
});

更好地为您的表单提供动态数据类

$(document).on('submit', '.myform', function(e) {
...
});