[英]Returning a PDF from an ASP.NET Core 2 Controller
I am trying to return a PDF file from my ASP.NET Core 2 controller. 我试图从我的ASP.NET Core 2控制器返回一个PDF文件。 I have this code (mostly borrowed from this SO question ):
我有这个代码(大多是从这个SO问题借来的):
var net = new System.Net.WebClient();
//a random pdf file link
var fileLocation = "https://syntera.io/documents/T&C.pdf";/
var data = net.DownloadData(fileLocation);
MemoryStream content = null;
try
{
content = new MemoryStream(data);
return new FileStreamResult(content, "Application/octet-stream");
}
finally
{
content?.Dispose();
}
This code above is part of a service class that my controller calls. 上面的代码是我的控制器调用的服务类的一部分。 This is the code from my controller.
这是我的控制器的代码。
public async Task<IActionResult> DownloadFile(string fileName)
{
var result = await _downloader.DownloadFileAsync(fileName);
return result;
}
But I keep getting ObjectDisposedException: Cannot access a closed Stream.
但我不断收到
ObjectDisposedException: Cannot access a closed Stream.
The try and finally block was an attempt to fix it , from another SO question . 试图和最后一个块试图修复它,从另一个SO问题。
The main question is A) Is this the right way to send a PDF file back to the browser and B) if it isn't, how can I change the code to send the pdf to the browser? 主要问题是A)这是将PDF文件发送回浏览器的正确方法吗?B)如果不是,我如何更改代码以将pdf发送到浏览器?
Ideally , I don't want to first save the file on the server and then return it to the controller. 理想情况下,我不想先将文件保存在服务器上,然后将其返回给控制器。 I'd rather return it while keeping everything in memory.
我宁愿把它留在记忆中。
The finally
will always get called ( even after the return
) so it will always dispose of the content stream before it can be sent to the client, hence the error. finally
将始终被调用( 即使在return
),因此它总是会在将内容流发送到客户端之前将其丢弃,因此会出错。
Ideally , I don't want to first save the file on the server and then return it to the controller.
理想情况下,我不想先将文件保存在服务器上,然后将其返回给控制器。 I'd rather return it while keeping everything in memory.
我宁愿把它留在记忆中。
Use a FileContentResult
class to take the raw byte array data and return it directly. 使用
FileContentResult
类获取原始字节数组数据并直接返回。
FileContentResult : Represents an
ActionResult
that when executed will write a binary file to the response.FileContentResult :表示一个
ActionResult
,它在执行时会将二进制文件写入响应。
async Task<IActionResult> DownloadFileAsync(string fileName){
using(var net = new System.Net.WebClient()) {
byte[] data = await net.DownloadDataTaskAsync(fileName);
return new FileContentResult(data, "application/pdf") {
FileDownloadName = "file_name_here.pdf"
};
}
}
No need for the additional memory stream 无需额外的内存流
You must specify : 您必须指定:
Response.AppendHeader("content-disposition", "inline; filename=file.pdf");
return new FileStreamResult(stream, "application/pdf")
For the file to be opened directly in the browser. 对于要在浏览器中直接打开的文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.