檔案上傳,iframe跨域資料提交的實現_javascript技巧

來源:互聯網
上載者:User

1、檔案上傳,圖片上傳,第三方uploadify外掛程式,http://www.uploadify.com/about/

2、用iframe上傳檔案,提交表單,主要思路就是:

 a、js建立form表單,iframe,添加到body裡,form的target要和iframe的name一致。

 b、form表單裡更新資料,submit提交

 c、如果上傳檔案,圖片,form裡面添加 input-file 元素,綁定onchange事件,js觸發,在onchange裡面添加submit事件

 d、關於回調:iframe提交成功後,返回的資料在iframe子頁面的裡面,可以這樣擷取,需要拆分:

$iframe[0].contentWindow.document.querySelector('body').innerHTML

代碼片:

 

var target = 'frameFile';var input = '<input type="file" name="file" onchange="changeImage()">' +  '<input name="appId" value="'+id+'">' +  '<input type="submit" name="submit" value="submit">';var $form = $('<form action="'+ url +'" target="'+ target +'" enctype="multipart/form-data" method="post" id="upImageForm" style="display:none">'+input+'</form>').appendTo('body');var $iframe = $('<iframe name="'+ target +'" style="display:none"></iframe>').appendTo('body');$form.find('input').eq(0).click();window.changeImage = function(){  $form.find('input').eq(-1).click();};//檢測iframe頁面load$iframe.load(function(e){  var str = $iframe[0].contentWindow.document.querySelector('body').innerHTML;  var data = spt(str);  $form.remove();  $iframe.remove();  callback(data);});function spt(str){  //字串拆成對象  var a = str.indexOf('{');  var b = str.indexOf('}');  var j = {};  var t = [];  var s = str.substring(a+1,b);  s = s.replace(/"/gi,'');  t = s.split(',');  for(var i=0; i<t.length; i++ ){    var tmp = t[i].split(':');    j[tmp[0]] = tmp[1];  };  return j;};

 2-c修正,以上代碼有bug:

手動觸發input-file的onchange事件,在事件裡面submit,這做法有問題。因為觸發onchange事件,選擇才開始,submit就已經提交了。

上傳功能,form表單元素只能放到html裡。

以上這篇檔案上傳,iframe跨域資料提交的實現就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.