duanhan9334 2014-12-16 16:03
浏览 42
已采纳

Yii:无法使用Ajax上传文件

After reading the accepted answer on this post, I am trying to implement the same but not able to figure out the problem. When I select a file, nothing is available in $_FILES on the server side. What am I doing wrong? I am using Apache 2.2.22, Yii 1.12

My view file

<form enctype="multipart/form-data" action='/webapp/index.php/emu/default/uploadFile' method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
    <input id="files" type="file" >
</form>
<script>
document.getElementById('files').addEventListener('change', function(e) {
    var file = this.files[0];
    var xhr = new XMLHttpRequest();
    xhr.file = file; // not necessary if you create scopes like this
    xhr.addEventListener('progress', function(e) {
        var done = e.position || e.loaded, total = e.totalSize || e.total;
        console.log('xhr progress: ' + (Math.floor(done/total*1000)/10) + '%');
    }, false);
    if ( xhr.upload ) {
        xhr.upload.onprogress = function(e) {
            var done = e.position || e.loaded, total = e.totalSize || e.total;
            console.log('xhr.upload progress: ' + done + ' / ' + total + ' = ' + (Math.floor(done/total*1000)/10) + '%');
        };
    }
    xhr.onreadystatechange = function(e) {
        if ( 4 == this.readyState ) {
            console.log(['xhr upload complete', e]);
        }
    };
    var url='/webapp/index.php/emu/default/uploadFile';
    xhr.open('post', url, true);
    xhr.send(file);
}, false);
</script>

Controller action:

public function actionUploadFile(){
    Yii::log(CJSON::encode($_FILES['files']));
}

Yii::log outputs following:

2014/12/16 19:59:29 [error] [php] Undefined index: files 
  • 写回答

1条回答 默认 最新

  • dongtao4787 2014-12-16 16:26
    关注

    To upload a file transparently via ajax you'll have to use a FormData object

    var file = this.files[0];
    var xhr = new XMLHttpRequest();
    var data = new FormData();
    data.append('files', file);
    ...
    xhr.send(data);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵