1

我想仅使用 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');
    }

}
4

1 回答 1

1

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

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

if (isset($_POST['upload'])) {
    ...
} else {
    die ('Error: AJAX cannot handle file uploads');
}
于 2013-04-20T21:41:56.337 回答