[C#] http如何在POST之後下載文件

原理

  • 要讓瀏覽器彈出另存爲的對話框,需要在http header裏面設置恰當的content-type。瀏覽器會根據response裏面的content-type來做不同的處理和響應
  • 要想指定下載的默認文件名,需要設置Content-Disposition這個header。
  • 要下載的文件,需要寫入response的http body裏面。想下載什麼內容,寫什麼內容。
  • Context.Response.End()會結束當前頁面請求的處理,避免Page_Load之後的filter寫額外的東西到http body去。

代碼

if (exportcsv == 1 && Context.Request.HttpMethod == "POST")
{
	Context.Response.ContentType = "text/csv";
	Context.Response.AddHeader("Content-Disposition", "attachment;filename=mydata.csv");

	foreach (DataRow row in ds.Tables[0].Rows)
	{
		Context.Response.Output.WriteLine(string.Format("{0},{1}", row["name"], row["age"]));
	}

	Context.Response.End();
			
	return;
}


另外,csv文件下載之後有可能會中文亂碼,可能會需要在寫csv正文之前先:


    var bom = System.Text.Encoding.UTF8.GetPreamble();
    context.Response.BinaryWrite(bom);





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章