asp.net mvc + javascript產生下載檔案的例子

來源:互聯網
上載者:User

近期做的是對現有項目進行重構。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矣

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.