通过表单上传文件(http://www.w3school.com.cn/php/php_file_upload.asp)在某些情况下已经不实用了(比如网页聊天室发送图片),经过几个小时的摸索,以下代码运用HTML5的FormData类和Ajax技术实现了后台的文件上传
html文件:index.html
<html>
<head>
</head>
<body>
<input type = 'file' id = 'file'/>
<!--
<input type = 'file' id = 'file' multiple />
如果这样写,就可以选中多个文件
都在document.getElementById("file").files数组里
-->
<button onclick = 'aa()'> ZZZ </button>
<script>
function GetXmlHttpObject()
//根据不同浏览器获取XmlHttp对象
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function aa()
{
var xx = document.getElementById("file").files[0];
var fd = new FormData() //FormData 顾名思义,表单也
//表单中添加项,当然也可以添加别的,比如 fd.append('author', 'kkk')
fd.append('file', xx)
var xhr = GetXmlHttpObject();//这里不直接用new XMLHttpRequest()避免浏览器不兼容
if (xhr == null)
{
alert ("Browser does not support HTTP Request")
return
}
//注意!! 如果fd的append的值是文件
//在trans.php中$_POST数组将看不到该属性
//而应该在$_FILES中查看!!
xhr.open("POST" ,"./trans.php" , true);
xhr.send(fd);
xhr.onload = function(e) {
if (this.status == 200) {
alert(this.responseText);
//由trans.php将上传的文件属性传过来,仅作参考
}
};
}
</script>
</body>
</html>
php文件 trans.php
<?php
//将PHP临时文件夹创建的副本剪切为第二个参数所指的文件
move_uploaded_file($_FILES["file"]["tmp_name"], "file/" . $_FILES["file"]["name"]);
print_r ($_FILES);
?>
新建名称为“file”的文件夹,上述代码将选中的文件复制到该文件夹中。