本文实例为大家分享了php表单文件iframe异步上传的具体代码,供大家参考,具体内容如下
1.表单中放置iframe元素;
2.文件上传控件内容变化的时候触发JS设置表单的action为处理文件上传的img_upload_process.php文件,并且将表单的target设置为iframe,让iframe去提交到服务器进行文件上传;
3.img_upload_process.php中处理文件上传成功后,将上传成功保存的文件路径回传给表单中隐藏域;
4.点击表单提交按钮的时,JS设置表单action为接收表单数据的form_process.php文件,表单的target设置为_self。
表单:asyn_uplaod.html
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>图片异步上传</title></head><body><!-- application/x-www-form-urlencoded 缺省编码类型 --><!-- multipart/form-data 多媒体传输协议 ,方法必须是post 既可以发送文本数据,也支持二进制数据上载 --><form action="" method="post" enctype="multipart/form-data"> 用户名: <input type="text" name="username" /><br /> 上传头像: <input type="file" id="avator" name="avator" onchange="startUpload(this.form)" /> <iframe frameborder='0' width='0' height='0' name="uploadframe"></iframe> <input type="hidden" id="save_path" name="save_path" /> <span id="loading"></span> <br /> <img width='100' height='100' id='uploaded_img' /> <br /> <input type="submit" name="submitted" value="提交" onclick="formSubmit(this.form)" /></form><script>function startUpload(formObj){ document.getElementById('loading').innerHTML = '上传中...'; formObj.action = 'img_upload_process.php'; formObj.target = 'uploadframe'; formObj.submit(); }function formSubmit(formObj) { formObj.action = 'form_process.php'; formObj.target = '_self'; //清空文件上传内容,防止重复提交 var fileObj = document.getElementById('avator') ; // for IE, Opera, Safari, Chrome if (fileObj.outerHTML) { fileObj.outerHTML = fileObj.outerHTML; } else { // FF(包括3.5) fileObj.value = ""; } formObj.submit(); }</script></body></html>
处理文件上传:img_upload_process.php
<?phpinclude 'Upload.class.php';$file = $_FILES['avator'];$upload = new Upload();//上传工具类对象if($save_path = $upload->up($file)){//上传成功 echo <<<STR <script> window.parent.document.getElementById('uploaded_img').src = "$save_path"; window.parent.document.getElementById('loading').innerHTML = '上传成功'; window.parent.document.getElementById('save_path').value = "$save_path"; </script>STR;}else{ $error = $upload->error(); echo <<<STR <script> window.parent.document.getElementById('uploaded_img').src = ""; window.parent.document.getElementById('loading').innerHTML = "上传失败: $error"; </script>STR;}
新闻热点
疑难解答