A-A+
Javascript利用iframe框架实现文件上传
iframe框架实现文件上传原理就是点击表单上传时我们在from的打开方式是在iframe模式中操作了,这个就非常的简单了,下面给各位把例子介绍一下吧。
- html
- <form name="multiform" id="multiform" action="multi-form-submit.php" method="POST" enctype="multipart/form-data">
- 姓名: <input type="text" name="name" value="Ravi"/> <br/>
- 年龄 :<input type="text" name="age" value="1" /> <br/>
- 头像 :<input type="file" name="photo" /><br/>
- <input type="button" id="multi-post" value="提交"></input>
- </form>
- <div id="multi-msg"></div>
- js
- <script>
- $(document).ready(function()
- {
- //获取返回的document
- function getDoc(frame) {
- var doc = null;
- // IE8 cascading access check
- try {
- if (frame.contentWindow) {
- doc = frame.contentWindow.document;
- }
- } catch(err) {
- }
- if (doc) { // successful getting content
- return doc;
- }
- try { // simply checking may throw in ie8 under ssl or mismatched protocol
- doc = frame.contentDocument ? frame.contentDocument : frame.document;
- } catch(err) {
- // last attempt
- doc = frame.document;
- }
- return doc;
- }
- function postToIframe(formObj,callback){
- $("#multi-msg").html("<img src='loading.gif'/>");
- var formURL = formObj.attr("action");
- //生成随机id
- var iframeId = 'unique' + (new Date().getTime());
- //生成空白的iframe
- var iframe = $('<iframe src="javascript:false;" name="'+iframeId+'" />');
- //掩藏iframe
- iframe.hide();
- //给iframe设置target
- formObj.attr('target',iframeId);
- //添加iframe 到 body
- iframe.appendTo('body');
- iframe.load(function(e){
- var doc = getDoc(iframe[0]);
- var docRoot = doc.body ? doc.body : doc.documentElement;
- var data = docRoot.innerHTML;
- //回调函数 用于接收 iframe 中的返回值
- callback.call(this,data);
- });
- }
- $("body").on('submit',"#multiform",function(e)
- { //提交数据到Iframe中并返回数据
- postToIframe($(this),function(data){
- alert(data);
- });
- });
- $("body").on('click',"#multi-post",function()
- {
- $("#multiform").submit();
- });
- }
- );
- </script>
- php
- <?php
- echo "FILES =".json_encode($_FILES)."<br><br>";
- echo "POST =".json_encode($_POST)."<br>";
- ?>