您的位置:首页 > Web前端 > JQuery

PHP服务器文件管理器开发小结(十):使用jQuery和iframe实现AJAX文件上传

2015-02-19 15:05 1416 查看
上一节讨论了文件下载,这一节继续讨论文件上传。

众所周知,前端上传文件比较简单的办法就是使用文件控件<input type="file"/>。然而,如果我们需要上传过程是AJAX的,亦即上传过程不刷新页面,仅反馈需要的信息,那就需要更加精巧的设计了。
首先是上传文件图片链接:
<li><a href="#" title="upload" onClick="onUploadFile()"><img src="images/upload48.png" class="topmenu" alt=""/></a></li>
客户端需要将使用jQueryUI为用户提供上传文件的对话框,并且为用户提供上传结果的反馈。下面给出onUploadFile响应:
function onUploadFile()
{
$('#dialogUploadFile').dialog({
height:'auto',
width:'auto',
position:{my:'center',at:'center',collision:'fit'},
modal:false,
draggable:true,
resizable:true,
title:"New File",
show:'slide',
hide:'explode',
buttons:{
OK: function() {
$("#frmUploadFile").submit();
setTimeout("$.post('query.php', {act:'refresh'}, function (data) {\
$('#spanDirTable').html(data);\
$( '#dialogUploadFile' ).dialog( 'close' );\
})",
1000);
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
}
这里有一个变化,表单的提交直接使用submit(),而之后的AJAX请求使用了setTimeout进行延迟,这样是为了让服务器有足够的时间接收和处理上传的文件。
对应的“原材料”也有变化:
<div id="dialogUploadFile" style="display:none">
<form id="frmUploadFile" method="post" target="frameAlert" action="query.php" enctype="multipart/form-data">
<input type="hidden" name="act" value="upload"/>
Select file to upload:<input type="file" name="newFile"/>
</form>
</div>
<iframe id="frameAlert" style="display:none"></iframe>
这里引用了一个<iframe>作为表单的target。这样,我们可以将上传文件的处理结果反馈到对应的frame中,并弹出alert提示。
对应的PHP处理:
case "upload":
echo "<head></head><body>";
$isDirContentView = false;
if (isset($_SESSION["currDir"]))
{
$strDirName = $_SESSION["currDir"];
}
else $strDirName = "/home";
$fileElemName = "newFile";
if (!isset($_FILES[$fileElemName]))
{
echo "<script>alert('Upload File Unreceived!);</script></body>";
break;
}
$newFile = $_FILES[$fileElemName];
$tmpFilePath = $newFile["tmp_name"];
$targetPath = $strDirName."/".$newFile["name"];
if ($tmpFilePath === false || file_exists($targetPath))
{
echo "<script>alert('Unable to start upload!');</script></body>";
break;
}
if (!move_uploaded_file($tmpFilePath, $targetPath))
{
echo "<script>alert('Unable to save upload file!');</script></body>";
break;
}
echo "<script>alert(\"Upload file '$tmpFilePath' saved succeed in '$targetPath!'\");</script></body>";
break;
PHP使用$_FILES对象访问表单上传的文件信息,其中$_FILES[$fileElemName]["tmp_name"]存放着上传文件的临时路径,$_FILES[$fileElemName]["name"]存放着上传文件名。使用move_uploaded_file函数可以将上传的文件移动到目标路径上。
注意到这里输出了<head>和<body>标签,这样才能在前端frame中正确的弹出alert。
具体效果:



本文出自 “Accplayer的小地方” 博客,请务必保留此出处http://accplaystation.blog.51cto.com/9917407/1614871
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: