A-A+

Javascript利用iframe框架实现文件上传

2016年01月07日 前端设计 暂无评论 阅读 4 views 次

iframe框架实现文件上传原理就是点击表单上传时我们在from的打开方式是在iframe模式中操作了,这个就非常的简单了,下面给各位把例子介绍一下吧。

  1. html  
  2. <form name="multiform" id="multiform" action="multi-form-submit.php" method="POST" enctype="multipart/form-data">  
  3.     姓名: <input type="text" name="name"  value="Ravi"/> <br/>  
  4.     年龄 :<input type="text" name="age"  value="1" /> <br/>  
  5.     头像 :<input type="file" name="photo" /><br/>  
  6.     <input  type="button" id="multi-post" value="提交"></input>  
  7.   
  8. </form>  
  9. <div id="multi-msg"></div>  
  10.   
  11. js  
  12. <script>  
  13. $(document).ready(function()  
  14. {  
  15.   
  16. //获取返回的document  
  17. function getDoc(frame) {  
  18.      var doc = null;  
  19.   
  20.      // IE8 cascading access check  
  21.      try {  
  22.          if (frame.contentWindow) {  
  23.              doc = frame.contentWindow.document;  
  24.          }  
  25.      } catch(err) {  
  26.      }  
  27.   
  28.      if (doc) { // successful getting content  
  29.          return doc;  
  30.      }  
  31.   
  32.      try { // simply checking may throw in ie8 under ssl or mismatched protocol  
  33.          doc = frame.contentDocument ? frame.contentDocument : frame.document;  
  34.      } catch(err) {  
  35.          // last attempt  
  36.          doc = frame.document;  
  37.      }  
  38.      return doc;  
  39.  }  
  40.   
  41. function postToIframe(formObj,callback){  
  42.     $("#multi-msg").html("<img src='loading.gif'/>");  
  43.     var formURL = formObj.attr("action");  
  44.   
  45.     //生成随机id  
  46.     var  iframeId = 'unique' + (new Date().getTime());  
  47.   
  48.     //生成空白的iframe  
  49.     var iframe = $('<iframe src="javascript:false;" name="'+iframeId+'" />');  
  50.   
  51.     //掩藏iframe  
  52.     iframe.hide();  
  53.   
  54.     //给iframe设置target  
  55.     formObj.attr('target',iframeId);  
  56.   
  57.     //添加iframe 到 body  
  58.     iframe.appendTo('body');  
  59.     iframe.load(function(e){  
  60.         var doc = getDoc(iframe[0]);  
  61.         var docRoot = doc.body ? doc.body : doc.documentElement;  
  62.         var data = docRoot.innerHTML;  
  63.         //回调函数 用于接收 iframe 中的返回值  
  64.         callback.call(this,data);  
  65.     });  
  66.   
  67. }  
  68.   
  69. $("body").on('submit',"#multiform",function(e)  
  70.     {    //提交数据到Iframe中并返回数据  
  71.         postToIframe($(this),function(data){  
  72.             alert(data);  
  73.         });  
  74.     });  
  75.   
  76. $("body").on('click',"#multi-post",function()  
  77. {  
  78.     $("#multiform").submit();  
  79. });  
  80.   
  81. }  
  82. );  
  83. </script>  
  84.   
  85. php  
  86. <?php  
  87.     echo "FILES =".json_encode($_FILES)."<br><br>";  
  88.     echo "POST =".json_encode($_POST)."<br>";  
  89. ?>  

给我留言