从 MemoryStream 返回时,ASP.net MVC ActionResult 损坏了 excel 文件
我的控制器中有以下操作
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许您需要在将内存流传递给结果之前倒回内存流(设置
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 toSave
its position will be at the end, not the beginning.