从 MemoryStream 返回时,ASP.net MVC ActionResult 损坏了 excel 文件

发布于 2025-01-01 07:26:01 字数 850 浏览 0 评论 0原文

我的控制器中有以下操作

public ActionResult DownloadExcel()
        {
            //create and populate Excel file here
            C1XLBook testBook = new C1XLBook(); 
            //populate it here

            MemoryStream ms = new MemoryStream();
            testBook.Save(ms, FileFormat.Biff8);

            return File(ms, "application/ms-excel", "test-file.xls");           
        }

打开文件时,我收到 Excel 消息,指出该文件与扩展名不匹配,并且文件打开时已损坏。

如果我将文件保存在硬盘驱动器上并从那里返回它,一切都很好:

return base.File(@"C:\LOGS\test-file.xls", "application/ms-excel", "test-excel.xls");

我最初认为 Save 函数在将其保存到 MemoryStream 时会损坏它,所以我保存并重新加载它,返回也很好给用户 - 当保存在硬盘上并从那里返回时,而不是从 MemoryStream

有什么想法吗?我不太喜欢将文件保存在硬盘上......此外我应该能够将其保存到 MemoryStream 中并从那里返回它?

我的一种预感是,也许 MemoryStream 不应该用于返回 MVC 中的文件,因为每个请求都是隔离的?

I have the following action inside my Controller

public ActionResult DownloadExcel()
        {
            //create and populate Excel file here
            C1XLBook testBook = new C1XLBook(); 
            //populate it here

            MemoryStream ms = new MemoryStream();
            testBook.Save(ms, FileFormat.Biff8);

            return File(ms, "application/ms-excel", "test-file.xls");           
        }

When opening the file, I get the Excel message saying that the file doesn't match the extension and the file opens up corrupted.

If I save the file on the hard drive and return it from there, everything is fine:

return base.File(@"C:\LOGS\test-file.xls", "application/ms-excel", "test-excel.xls");

I initially thought that the Save function corrupts it when saving it into the MemoryStream, so I saved and re-loaded it back and it was fine passing back to the user - when saved on the Hard Drive and returned from there, rather than from the MemoryStream

Any ideas? I am not too fond of saving the file on the Hard Drive....besides I should be able to save it into the MemoryStream and return it from there?

One hunch I have is that perhaps the MemoryStream should not be used to return files in MVC, since every request is isolated?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

↙温凉少女 2025-01-08 07:26:01

也许您需要在将内存流传递给结果之前倒回内存流(设置 ms.Position = 0;)?调用 Save 后,其位置将位于末尾,而不是开头。

Perhaps you need to rewind the memory stream (set ms.Position = 0;) before passing it to the result? After the call to Save its position will be at the end, not the beginning.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文