0

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 
Community
  • 1
  • 1
FaisalKhan
  • 2,026
  • 3
  • 20
  • 32

1 Answers1

0

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);
Musa
  • 89,286
  • 16
  • 105
  • 123
  • Can you please explain what this line does "var file = this.files[0]"? I tried to the same with jQuery , like this "var file = $("#files"); and then assign the "file" var to XHR but it failed. I am unable to understand why an array is formed within the scope of change event of the "files" HTML object. Thanks. – FaisalKhan Dec 19 '14 at 15:39
  • `this` is the file input field. `files` is the list of files that was selected. The array like notation is used to access the first file in the list, which is the only file if its not a multiple file input. The assignment is straightforward. – Musa Dec 19 '14 at 15:45
  • Thanks, now I understand. Cheers :) – FaisalKhan Dec 19 '14 at 15:48