简体   繁体   English

ASP.NET MVC FileResult损坏文件

[英]ASP.NET MVC FileResult is corrupting files

I've been trying to get my ASP.NET MVC website to export some data as an Excel file. 我一直试图让我的ASP.NET MVC网站将某些数据导出为Excel文件。 For hours I thought that NPOI was just producing garbage so I switched over to EPPlus. 几个小时以来,我以为NPOI只是在产生垃圾,所以我切换到EPPlus。 I tested it in LINQPad and it created a proper working XLSX file, so I moved the code over to the MVC app. 我在LINQPad中对其进行了测试,并创建了一个正常工作的XLSX文件,因此将代码移至MVC应用程序。 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. 偶然地,我偶然看到了temp目录,发现EPPlus创建的文件为3.87KB且运行良好,但是FileResult返回的文件为6.42KB,该文件已损坏。 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. 我在某处读到它是由服务器GZip压缩引起的,所以我将其关闭,并且没有任何效果。 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);
}

As far as I'm concerned there's an issue with the FileResult and it's accompanying methods. 就我而言, FileResult及其附带的方法存在问题。 I ended up "resolving" the issue by overriding the Response object: 我最终通过覆盖Response对象来“解决”该问题:

[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();
}

Try using the OpenRead from FileInfo to get a file stream and see if that works. 尝试使用FileInfoOpenRead来获取文件流,看看是否OpenRead

[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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM