使用AJAX上传文件 - xhr

时间:2013-02-02 12:59:36

标签: php xmlhttprequest

我正在尝试使用AJAX上传文件,但我的输出始终为空......

那么错误或代码中缺少什么?谢谢!

HTML:

<form id="data" method="post" enctype="multipart/form-data">
    <input name="file" type="file" />
    <input type="button" value="Upload" />
</form>
<progress></progress>

JS:

$(":file").bind('change blur', function(e) {
    var file = this.files[0];
    name = file.name;
    size = file.size;
    type = file.type;
    console.log(name);
    console.log(size);
    /**
        OUTPUT:
            2-years-anniversaryv1.png jquery.form.img.js:10
            18407 
    */
    var formData = new FormData($(this)[0]);
    $.ajax({
        url: '/upload',
        type: 'POST',
        xhr: function() {
            myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload) {
                myXhr.upload.addEventListener('progress', progress, false); 
            }
            return myXhr;
        },
        success: function(result)
        {
            console.log($.ajaxSettings.xhr().upload);
            alert(result);
        },
        data: formData,
        cache: false,
        contentType: false,
        processData: false
    });
});

function progress(e){
    if(e.lengthComputable){
        $('progress').attr({value:e.loaded,max:e.total});
    }
}

PHP:

private function upload_file() {

   $this->getLog(print_r($_FILES,true));

   $returnData = array("file" => 'asd');

   echo json_encode($returnData);

}

getLog输出:

Array
(
)

Array
(
)

Array
(
)

1 个答案:

答案 0 :(得分:1)

如果您通过AJAX上传,则需要使用fopen()访问该文件的内容:

<?php
$f = fopen('php://input','rb');
$target = fopen('file_name_here','wb');
while($chunk=fread($f,8192)){
    fwrite($target,$chunk);
}
fclose($f);
fclose($target);

此外,您需要使用FileReader类来阅读文件的内容:

var file = this.files[0];
var reader = new FileReader();
reader.onload = function(e){
    var xhr = new XMLHttpRequest();
    xhr.onload = function(){
        //upload finished
    }
    xhr.open('POST','path/to/upload.php',true);
    xhr.send(e.target.result);
}
reader.readAsArrayBuffer(file);