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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 python读取速度问题
  • ¥15 stm32f407使用DMA问题
  • ¥15 您好 这个API接口该怎么弄 网站搭建好了 API也有 现在就不知道该怎么填写API 不知道怎么用
  • ¥88 用uniapp写一个多端的程序,用到高德地图,用高德的JSAPI吗?
  • ¥20 关于#c++#的问题:水果店管理系统
  • ¥30 dbLinq最新版linq sqlite
  • ¥20 对D盘进行分盘之前没有将visual studio2022卸载掉,现在该如何下载回来
  • ¥15 完成虚拟机环境配置,还有安装kettle
  • ¥15 2024年全国大学生数据分析大赛A题:直播带货与电商产品的大数据分析 问题5. 请设计一份优惠券的投放策略,需要考虑优惠券的数量、优惠券的金额、投放时间段和投放商品种类等因素。求具体的python代码
  • ¥15 有人会搭建生鲜配送自营+平台的管理系统吗