ASP.NET MVC FileResult is corrupting files

2019-07-23 05:08发布

I've been trying to get my ASP.NET MVC website to export some data as an Excel file. For hours I thought that NPOI was just producing garbage so I switched over to EPPlus. I tested it in LINQPad and it created a proper working XLSX file, so I moved the code over to the MVC app. AGAIN, I get corrupted files. By chance I happened to look at the temp directory and saw that the file created by EPPlus is 3.87KB and works perfectly, but the FileResult is returning a file that's 6.42KB, which is corrupted. Why is this happening? I read somewhere that it was the server GZip compression causing it, so I turned it off, and it had no effect. Someone, please help me, I'm going out of my mind... Here's my code.

[HttpGet]
public FileResult Excel(
    CenturyLinkOrderExcelQueryModel query) {
    var file = Manager.GetExcelFile(query); // FileInfo

    return File(file.FullName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", query.FileName);
}

2条回答
Anthone
2楼-- · 2019-07-23 05:23

Try using the OpenRead from FileInfo to get a file stream and see if that works.

[HttpGet]
public FileResult Excel(CenturyLinkOrderExcelQueryModel query) {
    var file = Manager.GetExcelFile(query); // FileInfo
    var fileStream = file.OpenRead();
    return File(fileStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", query.FileName);
}
查看更多
做自己的国王
3楼-- · 2019-07-23 05:49

As far as I'm concerned there's an issue with the FileResult and it's accompanying methods. I ended up "resolving" the issue by overriding the Response object:

[HttpGet]
public void Excel(
    CenturyLinkOrderExcelQueryModel query) {
    var file = Manager.GetExcelFile(query);

    Response.Clear();
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AddHeader("Content-Disposition", "attachment; filename=" + query.FileName);
    Response.BinaryWrite(System.IO.File.ReadAllBytes(file.FullName));
    Response.Flush();
    Response.Close();
    Response.End();
}
查看更多
登录 后发表回答