C# .Net-Core 3.1
在我的 C# api 中,我在 FileStreamResult 中返回一个 pdf 文件,效果很好。
一般来说,我将流包装在 using 中,但是此代码失败并显示
Cannot access a closed Stream.
using (MemoryStream stream = new MemoryStream(byteArray))
{
fileStreamResult = new FileStreamResult(stream, "application/pdf");
}
return (ActionResult)fileStreamResult;
Run Code Online (Sandbox Code Playgroud)
所以我需要这样做:
var stream = new MemoryStream(byteArray);
fileStreamResult = new FileStreamResult(stream, "application/pdf");
return (ActionResult)fileStreamResult;
Run Code Online (Sandbox Code Playgroud)
我假设流需要保持打开状态,我应该担心内存泄漏还是 IIS 会关闭流吗?有更好的选择吗?
我有一个从字节数组中获取的FileContentResult,并希望将其转换为FileStreamResult.这可能吗?如果是这样,怎么样?
我需要构建一个方法,它将接收模型,从中构建excel(构建和接收部分完成没有问题),然后使用内存流导出(让用户下载它)(不将其保存在服务器上).我是ASP.NET和MVC的新手,所以我找到了指南并将其构建为一个教程项目:
public FileResult Download()
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "ID";
xlWorkSheet.Cells[1, 2] = "Name";
xlWorkSheet.Cells[2, 1] = "1";
xlWorkSheet.Cells[2, 2] = "One";
xlWorkSheet.Cells[3, 1] = "2";
xlWorkSheet.Cells[3, 2] = "Two";
var path = "C:\\Work-Work\\TestFolder\\XCLbuildTry1\\csharp-Excel.xls";
xlWorkBook.SaveAs(path);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
Marshal.ReleaseComObject(xlWorkSheet);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(xlApp);
return File(path, "application/vnd.ms-excel", "WidgetData.xlsx");
}
Run Code Online (Sandbox Code Playgroud)
现在我需要更改此代码以使此方法发送我的excel文件而不保存我的excel文件在服务器上.我试图在堆栈上谷歌一些指南和答案,但现在我无法找到一个解决方案,我可以实现.
我想我应该使用FileStreamResult,但所有指南都没有提供有关创建和插入文件的特定信息.
FileStreamResult在 SPA 网站(.NET Core 2、SPA React 模板)中使用来自 C# 的 a,我从我的端点请求一个文件,这会在 C# 中触发此响应:
var file = await _docService.GetFileAsync(token.UserName, instCode.Trim()
.ToUpper(), fileSeqNo);
string contentType = MimeUtility.GetMimeMapping(file.FileName);
var result = new FileStreamResult(file.File, contentType);
var contentDisposition = new ContentDispositionHeaderValue("attachment");
Response.Headers[HeaderNames.ContentDisposition] =
contentDisposition.ToString();
return result;
Run Code Online (Sandbox Code Playgroud)
返回的响应是使用处理的msSaveBlob(特别是对于 MS,但即使我使用createObjectURL不同的浏览器,这也是一个问题(是的,我已经尝试了多种解决方案,但似乎都没有工作)。这是我用来的代码发送请求,并FileStreamResult从服务器接收 PDF 。
var file = await _docService.GetFileAsync(token.UserName, instCode.Trim()
.ToUpper(), fileSeqNo);
string contentType = MimeUtility.GetMimeMapping(file.FileName);
var result = new FileStreamResult(file.File, contentType);
var contentDisposition = new ContentDispositionHeaderValue("attachment");
Response.Headers[HeaderNames.ContentDisposition] =
contentDisposition.ToString();
return result;
Run Code Online (Sandbox Code Playgroud)
问题是我得到的返回的 …