您当前的位置: 首页 > 学无止境 > CSS3|Html5 网站首页CSS3|Html5
利用html5的api实现非iframe的ajax文件上传
发布时间:2016-06-11 20:23:04编辑:雪饮阅读()
ajax也可以不用iframe模拟式上传文件了。
html:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function selfile(){
var fd=new FormData();
var pic=document.getElementsByTagName('input')[0].files[0];
fd.append('pic',pic);
var xhr = new XMLHttpRequest();
xhr.open('POST','04-upfile.php',true);
xhr.onreadystatechange=function (){
if(this.readyState==4){
document.getElementById('debug').innerHTML=this.responseText;
//上传文件成功后,可以获得文件资料路径(blob)
var tmpimg=document.createElement('img');
tmpimg.src=window.URL.createObjectURL(pic);
document.getElementsByTagName('body')[0].appendChild(tmpimg);
}
}
xhr.send(fd);
}
</script>
</head>
<body>
<input type="file" name="pic" onchange="selfile()"/>
<div id="debug"></div>
</body>
</html>
php:04-upfile.php
<?php
print_r($_FILES);
?>
关键字词:html5,ajax,文件上传