![](/img/trans.png)
[英]How to serve a file in ASP.NET Core while it's still being written
[英]Asp.Net Core: how to make the browser show file as being downloaded before it's sent
我有以下生成文件的操作:
public async Task<IActionResult> GetFile()
{
//some long running action to actually generate the content
//(e.g. getting data from DB for reporting)
await Task.Delay(10000);
return File(new byte[]{}, "application/octet-stream");
}
问题是当用户关注该链接时,在点击操作和显示文件的浏览器之间存在长时间的延迟。
我真正想要的是,ASP.Net发送带文件名的头文件(因此浏览器会向用户显示文件已开始下载)并在生成文件内容时延迟发送Body。 是否有可能做到这一点?
我尝试了以下方法:
public async Task GetFile()
{
HttpResponse response = this.HttpContext.Response;
response.ContentType = "application/octet-stream";
response.Headers["Content-Disposition"] = "inline; filename=\"Report.txt\"";
//without writing the first 8 bytes
//Chrome doesn't display the file as being downloaded
//(or ASP.Net doesn't actually send the headers).
//The problem is, I don't know the first 8 bytes of the file :)
await response.WriteAsync(string.Concat(Enumerable.Repeat("1", 8)));
await response.Body.FlushAsync();
await Task.Delay(10000);
await response.WriteAsync("1234567890");
}
上面的代码工作,如果我没有response.WriteAsync
,我会很高兴response.WriteAsync
前8个字节用于发送标头。
还有其他方法可以克服它吗?
实际上,有问题的代码可以正常工作。 问题是, 在发送8个字节之前 , Chrome不会将文件显示为已下载
但是,如果你想写类似的东西,可以考虑阅读Stephen Cleary的一些有用的抽象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.