我有以下操作正在生成文件:
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 发送带有文件名的标头(因此浏览器会向用户显示文件已开始下载(并在生成文件内容时延迟发送正文。可以这样做吗?
我尝试了以下方法:
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
前 8 个字节来发送标头,我会很高兴。
还有其他方法可以克服它吗?
实际上,有问题的代码工作正常。 问题是,Chrome在发送8字节之前不会将文件显示为正在下载
但是,如果你想写类似的东西,可以考虑阅读Stephen Cleary的文章,一些有用的抽象。