[英]Asp.Net Core: how to make the browser show file as being downloaded before it's sent
I have the following action that is generating a file: 我有以下生成文件的操作:
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");
}
The problem is that when user follows that link, there's a long delay between hitting an action and the browser displaying the file as being downloaded. 问题是当用户关注该链接时,在点击操作和显示文件的浏览器之间存在长时间的延迟。
What I actually want, is for ASP.Net to send headers with filename (so the browser would show to the user that file has started to download) and delay sending the Body while file contents is generated. 我真正想要的是,ASP.Net发送带文件名的头文件(因此浏览器会向用户显示文件已开始下载)并在生成文件内容时延迟发送Body。 Is it possible to do this?
是否有可能做到这一点?
I tried the following: 我尝试了以下方法:
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");
}
The code above works, and I'd be happy with it, if I didn't have to response.WriteAsync
first 8 bytes for headers to be sent. 上面的代码工作,如果我没有
response.WriteAsync
,我会很高兴response.WriteAsync
前8个字节用于发送标头。
Are there other ways to overcome it? 还有其他方法可以克服它吗?
Actually, the code in question works correctly. 实际上,有问题的代码可以正常工作。 The problem is, that Chrome doesn't show file as being downloaded until 8 bytes are sent
问题是, 在发送8个字节之前 , Chrome不会将文件显示为已下载
However, if you'd want to write something similar, consider reading Stephen Cleary's post few useful abstractions. 但是,如果你想写类似的东西,可以考虑阅读Stephen Cleary的一些有用的抽象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.