使用jQuery AJAX通过FormData上传文件

时间:2013-04-20 06:26:57

标签: php javascript jquery ajax html5

我想只使用jQuery上传一个文件,然后将上传表单替换为处理文件上传的PHP脚本的输出。

目前,在我点击提交后,我收到了PHP脚本的空白回复。我认为这是因为表格数据(文件和上传输入)被上传数据覆盖了?

非常感谢任何解决此问题的帮助!

这是我的代码:

HTML

<div id="container">
    <form id="form" enctype="multipart/form-data">
        <input name="file" type="file">
        <input type="hidden" name="upload">
    </form>
    <a href="javascript:void(0)" onclick="uploadData($('#form').serialize(), 'upload.php', '#container'); return false;">Upload &gt;</a>
</div>

的JavaScript

function uploadData(data, url, container) {

    var formData = new FormData($(data)[0]);

    $.ajax({
        type: 'POST',
        url: url,
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        success: function(response) {
            $(container).html(response);
        },
        error: function() {
            alert('Error!');
        },
    });

    return false;
};

PHP

if (isset($_POST['upload'])) {

    // check the file has been uploaded
    if (isset($_FILES['file'])) {

        // check if there was an error uploading the file
        if ($_FILES['file']['error'] > 0) {

            // display error
            echo 'Error: ' . $_FILES['file']['error'];
        } else {

            // move and store file (overwrite if it already exists)
            $fileName = '/upload/' . $_FILES['file']['name'];
            move_uploaded_file($_FILES['file']['tmp_name'], $fileName);

            echo 'File uploaded successfully';
        }
    } else {

        die ('Error: No file selected for upload');
    }

}

1 个答案:

答案 0 :(得分:1)

我认为ajax不能处理文件上传。您是否检查过该文件是否已实际上传?

如果确实如此,则您的回复为空,因为isset($_POST['upload'])会返回false。尝试添加最后一个else语句,检查我在说什么:

if (isset($_POST['upload'])) {
    ...
} else {
    die ('Error: AJAX cannot handle file uploads');
}