From: https://www.cnblogs.com/cang12138/p/5520758.html
第一種:最簡單的超鏈接方法,<a>標簽的href直接指向目標文件地址,這樣容易暴露地址造成盜鏈,這里就不說了
1、<a>標簽
<a href="~/Home/download?id=1">Click to get file</a>
2、后台C#下載
html:
<a href="~/Home/download?id=1">下載</a>
C#:
(1)返回filestream
public FileStreamResult download() { string fileName = "aaa.txt";//客戶端保存的文件名 string filePath = Server.MapPath("~/Document/123.txt");//路徑 return File(new FileStream(filePath, FileMode.Open), "text/plain", fileName);//“text/plain”是文件MIME類型 }
(2)返回file
public FileResult download() { string filePath = Server.MapPath("~/Document/123.txt");//路徑 return File(filePath, "text/plain", "1234.txt"); //1234.txt是客戶端保存的名字 }
(3)TransmitFile方法
public void download() { string fileName = "aaa.txt";//客戶端保存的文件名 string filePath = Server.MapPath("~/Document/123.txt");//路徑 FileInfo fileinfo = new FileInfo(filePath); Response.Clear(); //清除緩沖區流中的所有內容輸出 Response.ClearContent(); //清除緩沖區流中的所有內容輸出 Response.ClearHeaders(); //清除緩沖區流中的所有頭 Response.Buffer = true; //該值指示是否緩沖輸出,並在完成處理整個響應之后將其發送 Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName); Response.AddHeader("Content-Length", fileinfo.Length.ToString()); Response.AddHeader("Content-Transfer-Encoding", "binary"); Response.ContentType = "application/unknow"; //獲取或設置輸出流的 HTTP MIME 類型 Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); //獲取或設置輸出流的 HTTP 字符集 Response.TransmitFile(filePath); Response.End(); }
(4)Response分塊下載(服務器下載文件的大小有限制,更改iis等都無法解決,感覺可能跟服務器上的安全狗有關,最后用下面的方法解決下載問題)
public void download() { string fileName = "456.zip";//客戶端保存的文件名 string filePath = AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "Excel/123.zip"; System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath); if (fileInfo.Exists == true) { //每次讀取文件,只讀取1M,這樣可以緩解服務器的壓力 const long ChunkSize = 1048576; 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)); using (iStream)//解決文件占用問題,using 外 iStream.Dispose() 無法釋放文件 { 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; } iStream.Dispose(); iStream.Close(); } Response.Close(); Response.End(); } }
(5)流方式下載
public void download() { string fileName = "456.zip";//客戶端保存的文件名 string filePath = AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "Excel/123.zip";//以字符流的形式下載文件 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(); }
(6)ajax方法
要重點說說這個方法,ajax返回不了文件流,所以說用ajax調用上面任意一種后台方法都要出問題,下載不了文件。
所以,只能讓后台返回所需下載文件的url地址,然后調用windows.location.href。
優點:ajax可以傳好幾個參數(當然以json形式),傳100個都無所謂。你要是用<a href="網址?參數=值"></a>的方法傳100得寫死。。。(公司需求,至少要傳100多個參數)
缺點:支持下載exe,rar,msi等類型文件。對於txt則會直接打開,慎用!對於其他不常用的類型文件則直接報錯。
html:
<input type="button" id="downloadbutton"/>
ajax:
$("#downloadbutton").click(function() { $.ajax({ type: "GET", url: "/Home/download", data: { id: "1" }, dataType: "json", success: function(result) { window.location.target = "_blank"; window.location.href = result; } }) });
后台:
public string download() { string filePath = "Document/123.xls";//路徑 return filePath; }
(7)外網資源下載
string url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1494331750681&di=7bfc17bf6ef9b5abb02dfd2505a91e90&imgtype=0&src=http%3A%2F%2Fimg.article.pchome.net%2F00%2F35%2F62%2F34%2Fpic_lib%2Fs960x639%2FZhiwu36s960x639.jpg"; string fileName = url.Split('/')[url.Split('/').Length - 1];//客戶端保存的文件名 System.Net.WebClient wc = new System.Net.WebClient(); wc.Encoding = System.Text.Encoding.GetEncoding("gb2312"); byte[] bytes = wc.DownloadData(url); Response.Clear(); //二進制流數據(如常見的文件下載) 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();