傳統的表單上傳會導致頁面跳轉,體驗不佳。透過隱藏 iframe 搭配表單的 target 屬性,我們可以在不刷新頁面的情況下上傳檔案,並接收後台回傳的資料進行後續處理。
在頁面上加入一個隱藏的 iframe,將 form 的 target 指向該 iframe 的 id。送出時,檔案會以檔案流形式傳到後台,後台接收後進行自定義操作,回傳的資訊顯示在 iframe 中而不觸發跳轉。由於 iframe 事先隱藏,頁面外觀不會有任何變化。接著只需監聽 iframe 內容的變化,把內容傳給主視窗的 JS 方法做下一步處理即可。
<form id="input" action="importExcel.jhtml" method="post"
enctype="multipart/form-data" target="hiddenIFrame">
<input id="excelFile" name="file" type="file" />
<input type="submit" class="button" value="導入excel"/>
</form>
<iframe id="hiddenIFrame" name="hiddenIFrame" style="display:none;"></iframe>
$(function(){
$("#hiddenIFrame").load(function(){
var wnd = this.contentWindow;
var str = $(wnd.document.body).html();
callback(str);
});
});
function callback(info){
alert(info);
}
後台流程與傳統上傳一致:後台會依 input 元件的 name 值取得同名的檔案流(例如上例中 name 為 file,後台即收到名為 file 的檔案流),接收後即可進行自定義操作,例如解析 Excel、寫入資料庫,再把結果寫回 iframe。
這種做法的優點是完全不刷新頁面、使用者體驗流暢;實作時要注意 iframe 需先隱藏,並確保跨來源時不會有存取限制問題。