[英]Download large csv file (string) chunked or streaming
我想通過瀏覽器下載較大的csv文件(超過100 MB),但超時。 生成csv文件非常耗時,因此我無法在內存中全部讀取它或先寫入磁盤。
public IActionResult Download1()
{
var bytes = FetchBytes();
return File(bytes, "text/csv", "download1.csv");
}
FileStreamResult
需要提取內存中的所有流。
// GET or POST
public IActionResult Download()
{
var stream = FetchStream();
return new FileStreamResult(stream, "text/csv");
}
我嘗試編寫塊以響應,但我可以在瀏覽器中看到文件下載進度,但沒有得到文件下載或文件下載對話框。
// GET or POST
public ActionResult Download()
{
var response = this.Response;
var size = 4096;
foreach (var csvBatch in csvBatches)
{
byte[] bytes = Encoding.ASCII.GetBytes(csvBatch);
using (var ms = new MemoryStream(bytes))
{
var data = new byte[size];
var bytesRead = 0;
do
{
bytesRead = ms.Read(data, 0, size);
response.Body.Write(data, 0, readBytes);
response.Body.Flush();
} while (bytesRead > 0);
}
}
response.ContentType = "text/csv";
response.Headers.Add("Content-Disposition", $"attachment;filename=\"{fileName}\"");
// this streams the file but does not download or give file download dialog
}
Net Core沒有WriteFile(HttpResponseBase)
方法來覆蓋FileResult
,而方法是從Action寫入可以寫入Response.OutputStream
Action到Output Stream 。
我怎樣才能做到這一點?
您可以通過多種方式進行操作,也可以使用許多有用的類。 不要傷了你的頭,因為默認情況下它們會分塊。
我推薦的是StreamContent類。 它在構造函數上需要緩沖區大小。
這是示例。
public async Task<HttpResponseMessage> Download()
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
var stream = await GetStreamFromSomewhereMethod();
var content = new StreamContent(stream, 4096); //buffer is 4KB
response.Content = content;
return response;
}
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.