简单的XHR文件上传不传输文件

时间:2013-10-28 10:12:54

标签: javascript file-upload xmlhttprequest

upload.php脚本的$_FILES变量保持零长度。为什么文件没有发送?尽管如此,一切似乎都是有序的。我想删除表单并完全通过onchange处理程序执行上传。这可能吗?

<li>upload:<form id=upload enctype="multipart/form-data">
<input type=file id=file name=o onchange="submit()"/>
</form></li>

<script>
document.getElementById('upload').submit=function(){
var ul=document.getElementById('file');
if(ul.files.length>0){
  file=ul.files[0];
  var x=(window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHTTP');
  x.onreadystatechange=function(){if(x.readyState==4&&x.status==200){
    alert(x.responseText);}
  }
  x.open('post','upload.php',true);
  x.setRequestHeader('Content-Type','multipart/form-data');
  x.setRequestHeader('X-File-Name',file.name);
  x.setRequestHeader('X-File-Size',file.size);
  x.setRequestHeader('X-File-Type',file.type);
  x.send(file);
}
return false;
}

1 个答案:

答案 0 :(得分:1)

尝试FormData,它会自行设置标题。

var formData = new FormData();
formData.append("Filedata", document.getElementById("file").files[0]);

var x=(window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHTTP');
x.onreadystatechange=function(){if(x.readyState==4&&x.status==200){
   alert(x.responseText);}
}
x.open("POST", url);
x.send(formData);