[ASP.NET,MVC]檔案下載,檔案顯示在本網頁,以原始資料是byte為例

  • 2735
  • 0
  • 2016-04-21

摘要:[ASP.NET,MVC]檔案下載,檔案顯示在本網頁,以原始資料是byte為例

ASP.NET Web Form:
檔案下載:

System.Web.HttpContext.Current.Response.Clear(); 
System.Web.HttpContext.Current.Response.ClearHeaders(); 
System.Web.HttpContext.Current.Response.Buffer = false;
//常用contenttype:
//.doc:application/msword,.xls:application/vnd.ms-excel,.pdf:application/pdf,.jpg:image/jpeg
System.Web.HttpContext.Current.Response.ContentType = "application/pdf";
System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(strNewFileName));            
System.Web.HttpContext.Current.Response.AppendHeader("Content-Length", bytes.Length.ToString());
System.Web.HttpContext.Current.Response.BinaryWrite(bytes);          
System.Web.HttpContext.Current.Response.Flush();            
System.Web.HttpContext.Current.Response.End();

檔案顯示在本網頁:

System.Web.HttpContext.Current.Response.ClearHeaders();
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.Buffer = false;
System.Web.HttpContext.Current.Response.AddHeader("Content-Type", "application/pdf");
System.Web.HttpContext.Current.Response.AddHeader("Content-Length", bytes.Length.ToString());            
System.Web.HttpContext.Current.Response.BinaryWrite(bytes);
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.End();

ASP.NET MVC:寫法非常簡潔
檔案下載(程式碼寫在Controller裡面):

byte[] bytes = new byte[1024000];

string contentType = "";
if (fileExtention == ".pdf")
{
	contentType = "application/pdf";
}
else if (fileExtention == ".html" || fileExtention == ".htm")
{
	contentType = "text/html";
}
else
{

}

return File(bytes, contentType, "myFile.pdf");


檔案顯示在目前網頁(程式碼寫在Controller裡面):

byte[] bytes = new byte[1024000];

string contentType = "";
if (fileExtention == ".pdf")
{
	contentType = "application/pdf";
}
else if (fileExtention == ".html" || fileExtention == ".htm")
{
	contentType = "text/html";
}
else
{

}

return File(bytes, contentType);