上传原理很简单就是利用表单的打开方式为iframe的name名,这样就可以在当前页面的iframe打来了,实现文件上传,再利用js返回上传结果。

form target .在 action 属性中规定的页面会在新窗口中打开。如果是iframe,则在此iframe中打开。

phpAjaxUpload.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript">
function startUpload()
{
document.getElementById('processing').innerHTML="正在上传中"; }
function stopUpload(result)
{
var msg;
switch(result)
{
case 0:
msg="上传成功";
break;
case 1:
msg='文件大小超过限制';
break;
case 2:
msg='只能上传图片文件';
break;
case 3:
msg='move_uploaded_file失败';
break;
case 4:
msg="其他错误";
break;
default:
break;
}
document.getElementById('processing').innerHTML=msg;
alert(msg);
}
</script> </head> <body> <div id="processing">结果信息</div>
<form action="phpAjaxUpload2.php" method="post" enctype="multipart/form-data" target="uploadFrame" onsubmit="startUpload()">
<label for="myFile">上传文件</label>
<input type="hidden" name="MAX_FILE_SIZE" value="1024000" /><input type="file" name="myFile" id="myFile" />
<input type="submit" name="submit" value="上传" /> </form>
<iframe name="uploadFrame" style="width:0;height:0; border:0;"></iframe> </body>
</html>
上面的iframe中设置width,height为0,还有一点border为0,否则还是有一点边框。注意
MAX_FILE_SIZE要仔细设定,如果文件大小大于它,那么php端$_FILES['image']['size']就会为0.
phpAjaxUpload2.php
hello
<?php
$result;
if(isset($_POST['submit']))
{ $dir='asaph/';
$maxSize=1*pow(2,20);
$fileTypes=array('jpg','png','gif','bmp');
$myFileType=substr($_FILES['myFile']['name'],strpos($_FILES['myFile']['name'],'.')+1); if($_FILES['myFile']['size']>$maxSize)
{
$result=1;
}
else if(!in_array($myFileType,$fileTypes))
{
$result=2;
}
else if(is_uploaded_file($_FILES['myFile']['tmp_name']))
{
$dest=$dir.$_FILES['myFile']['name'];
if( @move_uploaded_file($_FILES['myFile']['tmp_name'],$dest))
{
$result=0;
}
else
{
$result=3;
}
}
else
{
$result=4;
}
} ?>
<script type="text/javascript">
window.top.stopUpload(<?php echo $result;?>);
</script>
更多:http://zccst.iteye.com/blog/1276920input file美化看:http://www.oschina.net/code/snippet_273800_20312