近期做的是對現有項目進行重構。WEB FROM改成MVC,其實也算是推倒重來了。
裡面有一個匯出功能,將資料輸出成txt檔案,供下載。原先的做法是有一個隱藏的iframe,在這個iframe的頁面中設定一個表單form,將相關參數提交到伺服器端;而在伺服器端,是真的產生一個檔案,然後再將檔案內容往用戶端推送。
好奇怪的做法啊。將內容匯出,讓使用者下載,不必真的組建檔案的,因為內容千變萬化,沒有一次產生,多次使用的可能和必要。完全可以將內容產生後,直接往用戶端推送。
其次,我理解原先為何要用一個隱藏的iframe。因為提交頁面會導致重新整理,為了避免頁面內容重新整理,於是搞了個隱藏的iframe,讓它來負責提交。好是好,就是要多搞一個頁面。
在新項目裡面,前端,form由JS動態產生;伺服器端,直接產生內容並推送:
前端:
| 代碼如下 |
複製代碼 |
<script type="text/javascript"> var f_pointXY = function () { function exportData() {//動態添加表單 var form = $("<form>"); form.attr('style', 'display:none'); form.attr('target', ''); form.attr('method', 'post'); form.attr('action', "@Url.StaticFile("~/Common/YongHai/ExportData/")" + $("#txt_SMID").val()); var input1 = $('<input>'); input1.attr('type', 'hidden'); input1.attr('name', 'isExportInput'); input1.attr('value', document.getElementById("chkInput").checked); var input2 = $('<input>'); input2.attr('type', 'hidden'); input2.attr('name', 'exportFormat'); input2.attr('value', document.getElementById("Select1").value); $('body').append(form); form.append(input1); form.append(input2); try { form.submit(); } catch (ex) { alert(ex); } form.remove();//用完即棄 } return { exportData: function () { exportData(); } }; }();
|
伺服器端:
| 代碼如下 |
複製代碼 |
[HttpPost] public ActionResult ExportData(int id, FormCollection collection) { string content = ...;//產生內容 Response.Clear(); Response.Buffer = false; Response.ContentType = "application/octet-stream"; Response.AppendHeader("content-disposition", "attachment;filename=" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt;"); Response.Write(content); Response.Flush(); Response.End(); return new EmptyResult(); } |
這樣,點擊按鈕匯出按鈕
| 代碼如下 |
複製代碼 |
<input type="button" value="匯出" class="btn mini minilt" onclick="f_pointXY.exportData()" />
|
之後,即可下載yyyy-MM-dd.txt矣