背景:使用文件流实现下载功能本机运行无问题,公司服务器部署运行无问题,甲方部署运行下载出错;
解决方案:使用分区下载实现该功能;
前端调用:
/*动态创建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();
}
}