[英]File not downloading from File or PhysicalFile IActionResult
[英]Return File from URL as IActionResult
我正在嘗試使用.Net Core和Razor頁面按下按鈕下載PDF。 這與我得到的一樣接近,但遇到了錯誤
“ObjectDisposedException:無法訪問已關閉的文件。System.IO.FileStream.ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancelToken)”。
如何正確返回文件?
測試.cshtml
@page
@model LoanCalculator.Pages.TestModel
@{
}
<form method="post">
<fieldset>
<input type="submit" value="Submit" id="submitButton" />
</fieldset>
</form>
測試.cshtml.cs
namespace LoanCalculator.Pages
{
public class TestModel : PageModel
{
public void OnGet()
{
}
public async Task<IActionResult> OnPostAsync()
{
using var httpClient = new HttpClient();
var url = "https://storage.googleapis.com/a2p-v2-storage/528a02ea-a399-4901-b8d6-d0494be68331";
byte[] imageBytes = await httpClient.GetByteArrayAsync(url);
using var fs = new FileStream("favicon.png", FileMode.Create);
fs.Write(imageBytes, 0, imageBytes.Length);
return File(fs, "application/pdf", "FileDownloadName.png");
}
}
問題是您正在處理 stream 而沒有將 stream 的 position 設置為零。
您只需將 stream 從請求轉移到響應,就可以提高 memory 的效率。
看看這個例子:
var targetFile = new Uri("https://www.example.com/file.pdf");
var resp = await _httpClientFactory.CreateClient().GetAsync(
targetFile, HttpCompletionOption.ResponseHeadersRead);
Response.ContentLength = resp.Content.Headers.ContentLength;
return File(await resp.Content.ReadAsStreamAsync(),
"application/pdf", Path.GetFileName(targetFile.LocalPath));
(這不是從內存中測試和寫入的)
此外,您應該使用IHttpClientFactory
而不是每次都創建一個新的HttpClient
。
一個例子:
// ...
using System.Net.Http;
// ...
namespace LoanCalculator.Pages
{
public class TestModel : PageModel
{
private readonly IHttpClientFactory _httpClientFactory;
public TestModel(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
}
}
在您的Startup.cs
中,添加以下內容:
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddHttpClient();
// ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.