Ajax文件上传 - 服务器端出错

时间:2014-03-06 17:52:02

标签: javascript php jquery ajax html5

我正在尝试通过HTML5 File API实现ajax文件上传。它基于Afzaal Ahmad Zeeshan对this问题的回答。

我基本上复制了他编写的整个代码,但无法使其工作。

此处的主要目的是能够将.xls.xlsx个文件上传到服务器,以便稍后使用PHPExcel与他们合作。

这是我的HTML:

<form class="form-uploadXLS" method="post" action="php/uploadXLS.php" enctype="multipart/form-data">
    <div class="form-group">
        <div class="col-md-12">
            <input type="file" name="xls" class="xls" />
        </div>
    </div>
    <input type="button" value="Upload" class="btn-uploadXLS" />
</form>
<progress></progress>

以下是jQuery事件处理程序,就像上面提到的答案一样:

文件输入onChange事件:

$('.xls').on('change', function () {
    var file = this.files[0];
    var fileName = file.name;
    var fileType = file.type;
    var fileSize = file.size;

    console.log("file name: " + fileName + ", type: " + fileType + ", size: " + fileSize);
});

上传按钮的onClick事件:

$('.btn-uploadXLS').on('click', function (event) {
    event.preventDefault();
    console.log("Upload button clicked");
    var formData = new FormData($('.form-uploadXLS')[0]);

    $.ajax({
        url: 'php/uploadXLS.php', //Server script to process data
        type: 'POST',
        xhr: function () { // Custom XMLHttpRequest
            var myXhr = $.ajaxSettings.xhr();
            if (myXhr.upload) { // Check if upload property exists
                myXhr.upload.addEventListener('progress', progressHandlingFunction, false); // For handling the progress of the upload
            }
            return myXhr;
        },
        //Ajax events
        beforeSend: function (stuff) {
            console.log("BeforeSend");
            console.log(stuff);
        },
        success: function (data) {
            console.log("Success!");
            console.log(data);
        },
        error: function (error) {
            console.log("Error!");
            console.log(error);
        },
        // Form data
        data: formData,
        //Options to tell jQuery not to process data or worry about content-type.
        cache: false,
        contentType: false,
        processData: false
    });
});

编辑从此处开始:

最后这是我打印出$ _FILES数组的PHP代码:

if(!empty($_FILES['xls'])) {
    echo '<pre>',print_r($_FILES,1),'</pre>';
}
else {
    die('POST ÜRES');
}

这是结果:

Array
(
    [xls] => Array
        (
            [name] => 
            [type] => 
            [tmp_name] => 
            [error] => 4
            [size] => 0
        )

)

由于某种原因,我无法访问错误消息,它只包含数字4。

我做错了什么?

1 个答案:

答案 0 :(得分:3)

对于您需要的文件

$_FILES['xls']不是$_POST

阅读Handling file uploads

<小时/> 要获得更多信息,只需打印数组

echo '<pre>',print_r($_FILES,1),'</pre>'

阅读php - file upload

Ajax File Upload with PHP, HTML5 File API and jQuery