在this帖子上阅读了接受的答案后,我试图实现相同但无法弄清楚问题。当我选择一个文件时,服务器端的$ _FILES中没有可用的东西。我究竟做错了什么?我正在使用Apache 2.2.22,Yii 1.12
我的观看文件
<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>
控制器操作:
public function actionUploadFile(){
Yii::log(CJSON::encode($_FILES['files']));
}
以下的Yii :: log输出:
2014/12/16 19:59:29 [error] [php] Undefined index: files
答案 0 :(得分:0)
要通过ajax透明地上传文件,您必须使用FormData对象
var file = this.files[0];
var xhr = new XMLHttpRequest();
var data = new FormData();
data.append('files', file);
...
xhr.send(data);