標籤:
public static void DownLoadFile(string FileFullPath) { if (!string.IsNullOrEmpty(FileFullPath) && FileExists(FileFullPath)) { FileInfo fi = new FileInfo(FileFullPath);//檔案資訊 FileFullPath = HttpUtility.UrlEncode(Path.GetFileName(FileFullPath)); //對檔案名稱編碼 FileFullPath = FileFullPath.Replace("+", "%20"); //解決空格被編碼為"+"號的問題 HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ContentType = "application/octet-stream"; HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileFullPath); HttpContext.Current.Response.AppendHeader("content-length", fi.Length.ToString()); //檔案長度 int chunkSize = 102400;//緩衝區大小,可根據伺服器效能及網路情況進行修改 byte[] buffer = new byte[chunkSize]; //緩衝區 using (FileStream fs = fi.Open(FileMode.Open)) //開啟一個檔案流 { while (fs.Position >= 0 && HttpContext.Current.Response.IsClientConnected) //如果沒到檔案尾並且客戶線上 { int tmp = fs.Read(buffer, 0, chunkSize);//讀取一塊檔案 if (tmp <= 0) break; //tmp=0說明檔案已經讀取完畢,則跳出迴圈 HttpContext.Current.Response.OutputStream.Write(buffer, 0, tmp);//向用戶端傳送一塊檔案 HttpContext.Current.Response.Flush();//保證緩衝全部送出 Thread.Sleep(10);//主線程休息一下,以釋放CPU } } } }
這是從某項目當中找到的一段代碼
在本機和測試環境 調用沒有問題
在實際生產環境當中 IIS給了檔案夾 USERS和IIS_IUSRS 讀取許可權 結果怎麼都無法下載檔案
原因:FileMode.Open 需要寫入許可權
MVC埰坑日記 檔案許可權