簡體   English   中英

Asp.Net Core:如何使瀏覽器顯示文件在發送之前被下載

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM