方式一:
/// <summary>
/// 檔案下載類
/// 調用1:DownLoadFile("/2003.xls", null);
/// 調用2:DownLoadFile("/2003.xls", "");
/// 調用3:DownLoadFile("/2003.xls", "temp.xls");
/// </summary>
/// <param name="filePath">檔案路徑(格式:/upload/2003.xls)</param>
/// <param name="filename">自訂檔案名稱(不想自訂檔案名稱請傳[ "" or null ] )</param>
public ActionResult DownFile(string filePath, string fileName)
- {
- filePath = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["AttachmentPath"] + filePath);
- FileStream fs = new FileStream(filePath, FileMode.Open);
- byte[] bytes = new byte[(int)fs.Length]; //以字元流的形式下載檔案
- fs.Read(bytes, 0, bytes.Length);
- fs.Close();
- Response.Charset = "UTF-8";
- Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
- Response.ContentType = "application/octet-stream"; //通知瀏覽器下載檔案而不是開啟
-
- Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(fileName));
- Response.BinaryWrite(bytes);
- Response.Flush();
- Response.End();
- return new EmptyResult();
-
- }
方式二:
public FileStreamResult DownFile(string filePath, string fileName)
{
string absoluFilePath = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["AttachmentPath"] + filePath);
return File(new FileStream(absoluFilePath, FileMode.Open), "application/octet-stream", Server.UrlEncode(fileName));
}
調用方式:
<a href="/Document/DownFile?filePath=@item.Value&fileName=@item.Key">下載</a>