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();
标签:文件,string,filePath,C#,几种,fileName,Response,下载 From: https://www.cnblogs.com/ning-xiaowo/p/16792303.html