asp.net mvc分区下载
背景:使用文件流实现下载功能本机运行无问题,公司服务器部署运行无问题,甲方部署运行下载出错;
解决方案:使用分区下载实现该功能;
前端调用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | /*动态创建form用于接收文件流 * **/ function getExce(ids) { var form = $("< form >"); form.attr('style', 'display:none'); form.attr('target', ''); form.attr('method', 'post'); //请求方式 form.attr('action', "/ISOA/exportData");//请求地址 var input1 = $('< input >');//将你请求的数据模仿成一个input表单 var input2 = $('< input >');//将你请求的数据模仿成一个input表单 var input3 = $('< input >');//将你请求的数据模仿成一个input表单 input1.attr('type', 'hidden'); input1.attr('name', 'val_Ids');//该输入框的name input1.attr('value', JSON.stringify(ids));//该输入框的值 $('body').append(form); form.append(input1); form.append(input2); form.append(input3); form.submit(); form.remove(); } |
原代码(文件流):
C#
public ActionResult DownloadExcel() { string fileName = "污水减免导入模板.xls";//客户端保存的文件名 string filePath = Server.MapPath("~/ExcelTemplate/污水减免导入模板.xls");//路径 return File(new FileStream(filePath, FileMode.Open), "application/ms-excel", fileName); }
分区下载:
C#
public void DownloadExcel() { string fileName = "污水减免导入模板.xls";//客户端保存的文件名 string filePath = Server.MapPath("~/ExcelTemplate/污水减免导入模板.xls");//路径 FileInfo fileInfo = new FileInfo(filePath); FileStream iStream = System.IO.File.OpenRead(filePath); try { if (fileInfo.Exists == true) { const long ChunkSize = 102400;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力 byte[] buffer = new byte[ChunkSize]; Response.Clear(); long dataLengthToRead = iStream.Length;//获取下载的文件总大小 Response.ContentType = "application/ms-excel"; 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; } } } finally { iStream.Close(); Response.Close(); } }
分类:
DOTNET
标签:
asp.net mvc
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!