简体   繁体   English

从ASP.NET Core 2控制器返回PDF

[英]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.

相关问题 返回 IAsyncEnumerable<T> 和来自 Asp.Net Core 控制器的 NotFound - Returning IAsyncEnumerable<T> and NotFound from Asp.Net Core Controller ASP.NET 核心 MVC:controller 返回在查询字符串上解析的 model - ASP.NET Core MVC : controller returning the model parsed on querystring Model 列表返回为 null 从视图到 controller Z9E0DA8438E1E38A1C30F4B76ZCE3 核心 - Model List returning as null from view to controller ASP.NET Core MVC 从 ASP.NET Core 中的 controller 返回 Content-Type 作为 application/javascript - Returning Content-Type as application/javascript from a controller in ASP.NET Core 从显式类型的 ASP.NET 核心返回 404 API controller(不是 IActionResult) - Returning a 404 from an explicitly typed ASP.NET Core API controller (not IActionResult) ASP.NET 铁芯返回 - ASP.NET Core Returning 从控制器返回Json数据以查看ASP.NET MVC - Returning Json Data From Controller to View ASP.NET MVC 从控制器操作返回RDF-ASP.NET MVC - Returning RDF from Controller Action - ASP.NET MVC 从我的 React 应用程序调用我的 asp.net 核心 controller 并在尝试获取它时返回 null 时不会生成 Cookie - Cookie does not generate when calling my asp.net core controller from my react app and returning null when try to get it 在 asp.net core 上使用来自不同项目的另一个控制器 - Use another controller from different project on asp.net core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM