原先程式碼 ↓
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Response.Clear(); | |
Response.Buffer = true; | |
Response.Charset = ""; | |
Response.Cache.SetCacheability(HttpCacheability.NoCache); | |
Response.ContentType = contentType; | |
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName); | |
Response.BinaryWrite(bytes); | |
Response.Flush(); |
於程式碼中加上「 Response.AppendHeader("Content-Length", bytes.Length.ToString());」
bytse就是你所要輸出資料的byte陣列,透過.Length來得知此檔案的大小。
加上去之後,.docx、.xlsx等檔案,使用者下載後即可正常開啟。
修改後的程式碼 ↓
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Response.Clear(); | |
Response.Buffer = true; | |
Response.Charset = ""; | |
Response.Cache.SetCacheability(HttpCacheability.NoCache); | |
Response.ContentType = contentType; | |
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName); | |
Response.AppendHeader("Content-Length", bytes.Length.ToString());//HTTP標頭增加檔案大小資訊 | |
Response.BinaryWrite(bytes); | |
Response.Flush(); |
如我有說明錯誤、或有其他解決辦法,歡迎留言或來信指教。
參考來源:c# 下载.xlsx文件出错解决方法