http://www.cnblogs.com/zcttxs/archive/2012/05/21/2511947.html
http://www.cnblogs.com/flashlm/archive/2009/07/25/file_stream_write_method.html
http://www.cnblogs.com/liang--liang/archive/2012/10/20/2732745.html
推薦:https://www.cnblogs.com/xiongze520/p/10417472.html
一、MVC下載
方式一:
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)); }
方式二:
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(); }
View調用:
<a href="/Document/DownFile?filePath=@item.Value&fileName=@item.Key">下載</a>
二、其他下載
aspx頁面:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="上傳和下載文件.aspx.cs" Inherits="上傳和下載文件" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>無標題頁</title> </head> <body> <form id="form1" runat="server"> <asp:FileUpload ID="homeworkFile" runat="server" /> <asp:Button ID="btnAdd" runat="server" Text="上傳" OnClick="btnAdd_Click"/></br> <asp:Button ID="btndownfile" runat="server" Text="下載方法一:TransmitFile" onclick="btndownfile_Click" /></br> <asp:Button ID="btndownfilebyWriteFile" runat="server" Text="下載方法二:WriteFile" onclick="btndownfilebyWriteFile_Click" /></br> <asp:Button ID="btndownfilebyWriteFile2" runat="server" Text="下載方法三:WriteFile分塊" onclick="btndownfilebyWriteFile2_Click" /><br /> <asp:Button ID="btndownfilebystream" runat="server" Text="下載方法四:流方式下載" onclick="btndownfilebystream_Click" /> </form> </body> </html>
aspx后台代碼:

using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.IO; public partial class 上傳和下載文件 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnAdd_Click(object sender, EventArgs e) { //文件原名 string fileName = Path.GetFileName(this.homeworkFile.FileName); //文件新名字=文件原名+當前時間 string newFileName = fileName.Substring(0, fileName.IndexOf('.')) + DateTime.Now.ToString("yyyyMMddhhmmss"); //給文件名加后綴名 newFileName += fileName.Substring(fileName.IndexOf('.'), fileName.Length - fileName.IndexOf('.')); //獲得文件存儲的路徑名 string Url = ConfigurationManager.AppSettings["ResoursePath"] + ConfigurationManager.AppSettings["RESHomeworkContentPath"] + @"\" + newFileName; //驗證文件大小 if (this.IsFileSizeLessMax()) { //驗證文件的類型 if (this.isTypeOk(Url)) { //驗證文件存儲的路徑是否存在 string pathStr = ConfigurationManager.AppSettings["ResoursePath"] + ConfigurationManager.AppSettings["RESHomeworkContentPath"]; if (!Directory.Exists(pathStr)) //如果不存在路徑 { Directory.CreateDirectory(pathStr); //創建路徑 } if (!Url.Equals("")) //如果有上傳文件 { FileUpload fileUpLoad = new FileUpload(); //1.存放文件 // fileUpLoad.SaveAs(Url); homeworkFile.PostedFile.SaveAs(Url); } } } } /// <summary> /// 驗證上傳文件是否超過規定的最大值 /// </summary> /// <returns></returns> private bool IsFileSizeLessMax() { //返回值 bool result = false; if (this.homeworkFile.HasFile) //如果上傳了文件 { //獲取上傳文件的允許最大值 long fileMaxSize = 1024 * 1024; try { fileMaxSize *= int.Parse(ConfigurationManager.AppSettings["FileUploadMaxSize"].Substring(0, ConfigurationManager.AppSettings["FileUploadMaxSize"].Length - 1)); } catch (Exception ex) { //this.WriteException("UserPotal:Homework", ex); } if (this.homeworkFile.PostedFile.ContentLength > int.Parse(fileMaxSize.ToString())) //如果文件大小超過規定的最大值 { //this.ShowMessage("文件超過規定大小。"); } else { result = true; } } else //如果沒有上傳的文件 { result = true; } return result; } /// <summary> /// 驗證文件類型的方法 /// </summary> /// <param name="fileName"></param> /// <returns></returns> private bool isTypeOk(string fileName) { //返回結果 bool endResult = false; //驗證結果 int result = 0; if (!fileName.Equals("")) //如果有上傳文件 { //允許的文件類型 string[] fileType = null; try { fileType = ConfigurationManager.AppSettings["FileType"].Split(','); } catch (Exception ex) { //this.ShowMessage("獲取配置文件信息出錯"); //this.WriteException("AdminProtal:Homework", ex); } fileName = fileName.Substring(fileName.LastIndexOf('.'), fileName.Length - fileName.LastIndexOf('.')); for (int i = 0; i < fileType.Length; i++) { if (fileType[i].Equals(fileName)) //如果是合法文件類型 { result++; } } if (result > 0) { endResult = true; } } else //如果沒有上傳文件 { endResult = true; } return endResult; } //下載方法一 protected void btndownfile_Click(object sender, EventArgs e) { /* 微軟為Response對象提供了一個新的方法TransmitFile來解決使用Response.BinaryWrite 下載超過400mb的文件時導致Aspnet_wp.exe進程回收而無法成功下載的問題。 代碼如下: */ Response.ContentType = "application/x-zip-compressed"; Response.AddHeader("Content-Disposition", "attachment;filename=DBintegrate20120521030107.txt"); string filename = Server.MapPath("BJNetwork/Data/DBintegrate20120521030107.txt"); Response.TransmitFile(filename); } //下載方法二 protected void btndownfilebyWriteFile_Click(object sender, EventArgs e) { /* using System.IO; */ string fileName = "DBintegrate20120521030107.txt";//客戶端保存的文件名 string filePath = Server.MapPath("BJNetwork/Data/DBintegrate20120521030107.txt");//路徑 FileInfo fileInfo = new FileInfo(filePath); Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName); Response.AddHeader("Content-Length", fileInfo.Length.ToString()); Response.AddHeader("Content-Transfer-Encoding", "binary"); Response.ContentType = "application/octet-stream"; Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); Response.WriteFile(fileInfo.FullName); Response.Flush(); Response.End(); } //下載方法三 protected void btndownfilebyWriteFile2_Click(object sender, EventArgs e) { string fileName = "前台老師和學生界面對比20120521034329.rar";//客戶端保存的文件名 string filePath = Server.MapPath("BJNetwork/Data/前台老師和學生界面對比20120521034329.rar");//路徑 System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath); if (fileInfo.Exists == true) { const long ChunkSize = 102400;//100K 每次讀取文件,只讀取100K,這樣可以緩解服務器的壓力 byte[] buffer = new byte[ChunkSize]; Response.Clear(); System.IO.FileStream iStream = System.IO.File.OpenRead(filePath); long dataLengthToRead = iStream.Length;//獲取下載的文件總大小 Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName)); while (dataLengthToRead > 0 && Response.IsClientConnected) { int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//讀取的大小 Response.OutputStream.Write(buffer, 0, lengthRead); Response.Flush(); dataLengthToRead = dataLengthToRead - lengthRead; } Response.Close(); } } //下載方法四 protected void btndownfilebystream_Click(object sender, EventArgs e) { string fileName = "前台老師和學生界面對比20120521034329.rar";//客戶端保存的文件名 string filePath = Server.MapPath("BJNetwork/Data/前台老師和學生界面對比20120521034329.rar");//路徑 //以字符流的形式下載文件 FileStream fs = new FileStream(filePath, FileMode.Open); byte[] bytes = new byte[(int)fs.Length]; fs.Read(bytes, 0, bytes.Length); fs.Close(); Response.ContentType = "application/octet-stream"; //通知瀏覽器下載文件而不是打開 Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); Response.BinaryWrite(bytes); Response.Flush(); Response.End(); } }
web配置文件:
<appSettings> <!--上傳文件的路徑--> <add key="ResoursePath" value="D:\IbeaconShow\BJNetwork"/> <add key="RESHomeworkContentPath" value="\Data"/> <!--可上傳文件的大小--> <add key="FileUploadMaxSize" value="20M"/> <!--可上傳文件類型 --> <add key="FileType" value=".zip,.txt,.doc,.rar,.xls,.rtf,.xlsx,.docx,.png"/> </appSettings> <system.web> <!--修改asp.net默認上傳文件的大小--> <httpRuntime executionTimeout="300" maxRequestLength="409600" useFullyQualifiedRedirectUrl="false"/> </system.web>
相關文章:https://www.cnblogs.com/carekee/articles/2094675.html
IIS中上傳大小的修改
1、首先要到進程中把IIS服務關了,即把inetinfo.exe進程關了,不然里面的文件不給你更改的喲~~~
2、在系統目錄中找到:windows/system32/inesrv/metabase.xml”文件,找個文本編輯器打開他,我都用 EditPuls(這家伙不錯,帶字體色彩的),Ctrl+F 找到AspMaxRequestEntityAllowed="204800"這一項,這就是iis上傳文件的默認大小了,默認為204800Byte, 也就是200KB,將它改為你需要的大小就可以了!
ASP.NET文件下載各種方式比較:對性能的影響、對大文件的支持、對斷點續傳和多線程下載的支持
asp.net里提供了多種方式,從服務器端向客戶端寫文件流,實現客戶端下載文件。這種技術在做防下載系統時比較有用處。
主些技術主要有:WriteFile、TransmitFile和BinaryWrite
其中WriteFilet和BinaryWrite出現得比較早,對文件流的輸出可以啟動作用,但由於都是將整個文件讀到內存后再往客戶端寫,因此會占用大量的內存資源,特別是要下載的文件比較大時,影響asp.net應用的穩定運行。
TransmitFile是為了彌補WriteFile和BinaryWrite的不足才出現的方法,比WriteFile和BinaryWrite更加的穩定強大,對大文件的支持也不錯。但其也有不足之處,對斷點續傳的支持不行,一個大的文件如果一次性沒有下載完成的話,就需要從頭再來。
那么一個對性能影響小、支持大文件下載、支持斷點續傳甚至是多線程下載程序還是需要自己來寫的。其實BinaryWrite和WriteFile之所以會影響性能,是因為將整個文件讀到內存后再往客戶端寫,那么我們可以控制他的輸出方式,一次只讀一塊內容到內存,再往客戶端寫,這些就可以自定義下載的和個細節了。下面提供一個相對不錯的下載函數供大家參考。
/// <summary> /// 下載文件,支持大文件、續傳、速度限制。支持續傳的響應頭Accept-Ranges、ETag,請求頭Range 。 /// Accept-Ranges:響應頭,向客戶端指明,此進程支持可恢復下載.實現后台智能傳輸服務(BITS),值為:bytes; /// ETag:響應頭,用於對客戶端的初始(200)響應,以及來自客戶端的恢復請求, /// 必須為每個文件提供一個唯一的ETag值(可由文件名和文件最后被修改的日期組成),這使客戶端軟件能夠驗證它們已經下載的字節塊是否仍然是最新的。 /// Range:續傳的起始位置,即已經下載到客戶端的字節數,值如:bytes=1474560- 。 /// 另外:UrlEncode編碼后會把文件名中的空格轉換中+(+轉換為%2b),但是瀏覽器是不能理解加號為空格的,所以在瀏覽器下載得到的文件,空格就變成了加號; /// 解決辦法:UrlEncode 之后, 將 "+" 替換成 "%20",因為瀏覽器將%20轉換為空格 /// </summary> /// <param name="httpContext">當前請求的HttpContext</param> /// <param name="filePath">下載文件的物理路徑,含路徑、文件名</param> /// <param name="speed">下載速度:每秒允許下載的字節數</param> /// <returns>true下載成功,false下載失敗</returns> public static bool DownloadFile(HttpContext httpContext, string filePath, long speed) { httpContext.Response.Clear(); bool ret = true; try { #region --驗證:HttpMethod,請求的文件是否存在 switch (httpContext.Request.HttpMethod.ToUpper()) { //目前只支持GET和HEAD方法 case "GET": case "HEAD": break; default: httpContext.Response.StatusCode = 501; return false; } if (!File.Exists(filePath)) { httpContext.Response.StatusCode = 404; return false; } #endregion #region 定義局部變量 long startBytes = 0; long stopBytes = 0; int packSize = 1024 * 10; //分塊讀取,每塊10K bytes string fileName = Path.GetFileName(filePath); FileStream myFile = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); BinaryReader br = new BinaryReader(myFile); long fileLength = myFile.Length; int sleep = (int)Math.Ceiling(1000.0 * packSize / speed);//毫秒數:讀取下一數據塊的時間間隔 string lastUpdateTiemStr = File.GetLastWriteTimeUtc(filePath).ToString("r"); string eTag = HttpUtility.UrlEncode(fileName, Encoding.UTF8) + lastUpdateTiemStr;//便於恢復下載時提取請求頭; #endregion #region --驗證:文件是否太大,是否是續傳,且在上次被請求的日期之后是否被修改過 if (myFile.Length > long.MaxValue) {//-------文件太大了------- httpContext.Response.StatusCode = 413;//請求實體太大 return false; } if (httpContext.Request.Headers["If-Range"] != null)//對應響應頭ETag:文件名+文件最后修改時間 { //----------上次被請求的日期之后被修改過-------------- if (httpContext.Request.Headers["If-Range"].Replace("\"", "") != eTag) {//文件修改過 httpContext.Response.StatusCode = 412;//預處理失敗 return false; } } #endregion try { #region -------添加重要響應頭、解析請求頭、相關驗證 httpContext.Response.Clear(); if (httpContext.Request.Headers["Range"] != null) {//------如果是續傳請求,則獲取續傳的起始位置,即已經下載到客戶端的字節數------ httpContext.Response.StatusCode = 206;//重要:續傳必須,表示局部范圍響應。初始下載時默認為200 string[] range = httpContext.Request.Headers["Range"].Split(new char[] { '=', '-' });//"bytes=1474560-" startBytes = Convert.ToInt64(range[1]);//已經下載的字節數,即本次下載的開始位置 if (startBytes < 0 || startBytes >= fileLength) {//無效的起始位置 return false; } if (range.Length == 3) { stopBytes = Convert.ToInt64(range[2]);//結束下載的字節數,即本次下載的結束位置 if (startBytes < 0 || startBytes >= fileLength) { return false; } } } httpContext.Response.Buffer = false; httpContext.Response.AddHeader("Content-MD5", FileHash.MD5File(filePath));//用於驗證文件 httpContext.Response.AddHeader("Accept-Ranges", "bytes");//重要:續傳必須 httpContext.Response.AppendHeader("ETag", "\"" + eTag + "\"");//重要:續傳必須 httpContext.Response.AppendHeader("Last-Modified", lastUpdateTiemStr);//把最后修改日期寫入響應 httpContext.Response.ContentType = "application/octet-stream";//MIME類型:匹配任意文件類型 httpContext.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8).Replace("+", "%20")); httpContext.Response.AddHeader("Content-Length", (fileLength - startBytes).ToString()); httpContext.Response.AddHeader("Connection", "Keep-Alive"); httpContext.Response.ContentEncoding = Encoding.UTF8; if (startBytes > 0) {//------如果是續傳請求,告訴客戶端本次的開始字節數,總長度,以便客戶端將續傳數據追加到startBytes位置后---------- httpContext.Response.AddHeader("Content-Range", string.Format("bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength)); } #endregion #region -------向客戶端發送數據塊------------------- br.BaseStream.Seek(startBytes, SeekOrigin.Begin); int maxCount = (int)Math.Ceiling((fileLength - startBytes + 0.0) / packSize);//分塊下載,剩余部分可分成的塊數 for (int i = 0; i < maxCount && httpContext.Response.IsClientConnected; i++) {//客戶端中斷連接,則暫停 httpContext.Response.BinaryWrite(br.ReadBytes(packSize)); httpContext.Response.Flush(); if (sleep > 1) Thread.Sleep(sleep); } #endregion } catch { ret = false; } finally { br.Close(); myFile.Close(); } } catch { ret = false; } return ret; }