原链接:https://www.cnblogs.com/wangdetian168/articles/1216690.html
如图:下面代码是文件较小时的代码,用着没问题,但是文件超过了1G后发现下载出错了,找到了上面链接的下载大文件的代码,修改过后竟然能用。
源码:
//FileStreamResult:小文件下载时返回的数据类型 public void DownloadBackup(string id) { //try //{ // var data = this.CreateService<IDbBackupAppService>().GetOne(id); // var path = Server.MapPath("~/Resource/DbBackup/" + data.F_FileName); // var name = Path.GetFileName(path); // //文件过大(> 1G)时下面代码抛出异常:算术运算中发生溢出或下溢 // return File(new FileStream(path, FileMode.Open), "application/octet-stream", Server.UrlEncode(name)); //} //catch (Exception ex) //{ // Sys_Log entity = this.InsertLog(LogType.Exception, "系统管理/数据备份", "下载备份文件异常,异常信息[" + ex.Message + "]"); // this.CreateService<ILogAppService>().insertLog(entity); // throw new Exception(ex.ToString()); //} Debug.WriteLine("开始时间:" + DateTime.Now); //文件过大(>1G)处理 var data = this.CreateService<IDbBackupAppService>().GetOne(id); var filepath = Server.MapPath("~/Resource/DbBackup/" + data.F_FileName); Stream iStream = null; byte[] buffer = new Byte[102400]; int length; //总共要读取的字节长度 long dataToRead; string filename = Path.GetFileName(filepath); try { //打开文件 iStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read); dataToRead = iStream.Length; Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment; filename=" + filename); //读取文件 while (dataToRead > 0) { //验证客户端是否链接 if (Response.IsClientConnected) { //读取数据到buffer里 length = iStream.Read(buffer, 0, 102400); //把buffer中的数据写入到输出流 Response.OutputStream.Write(buffer, 0, length); //刷新 Response.Flush(); buffer = new Byte[102400]; dataToRead = dataToRead - length; } else { //防止无限循环 dataToRead = -1; } } } catch (Exception ex) { //捕捉异常信息 Response.Write("Error : " + ex.Message); Sys_Log entity = this.InsertLog(LogType.Exception, "系统管理/数据备份", "下载备份文件异常,异常信息[" + ex.Message + "]"); this.CreateService<ILogAppService>().insertLog(entity); //throw new Exception(ex.ToString()); } finally { if (iStream != null) { //关闭文件 iStream.Close(); } } Debug.WriteLine("结束时间:" + DateTime.Now); }