我有一个Web API端点,它通过首先下载文件,然后返回字节数组来为我提供文件.
此代码可以工作,但会首先将整个文件(无论它有多大)加载到内存中.
有没有办法简单地返回与我用来下载httpClient
文件的流相同的流?
工作代码的简化示例:
[HttpGet("file")]
public async Task<IActionResult> DownloadFile(string url)
{
using var httpClient = new HttpClient();
using var response = await httpClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsByteArrayAsync();
var cd = new System.Net.Mime.ContentDisposition
{
FileName = "myFile.pdf",
// always prompt the user for downloading, set to true if you want
// the browser to try to show the file inline
Inline = false,
};
Response.Headers.Add("Content-Disposition", cd.ToString());
var mediaType = response.Content.Headers.ContentType.MediaType;
return File(content, mediaType);
}
return NotFound();
}
我已经try 过的(也算是有效的):
using var httpClient = new HttpClient();
using var response = await httpClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
using (var content = await response.Content.ReadAsStreamAsync())
{
content.Position = 0;
var cd = new System.Net.Mime.ContentDisposition
{
FileName = "myFile.pdf",
// always prompt the user for downloading, set to true if you want
// the browser to try to show the file inline
Inline = false,
};
Response.Headers.Add("Content-Disposition", cd.ToString());
var mediaType = response.Content.Headers.ContentType.MediaType;
return File(content, mediaType);
}
但这给了我ObjectDisposedException: cannot access a closed stream
美元.
请问有什么办法可以完成我想做的事吗?