我正在嘗試向用戶提供一個檔案,該檔案打包在服務器上的 zip 存檔中。該專案是 ASP.NET Core 5.0 MVC 專案。
我設法通過使用ZipArchiveEntry.Open()并將其復制到記憶體流來做到這一點。
string zipFile = @"D:\all_installs.zip";
using (FileStream fs = new FileStream(zipFile, FileMode.Open))
{
using (ZipArchive zip = new ZipArchive(fs))
{
ZipArchiveEntry entry = zip.Entries.FirstOrDefault(x => x.FullName == "downloadable file.iso");
string name = entry.FullName;
string baseName = Path.GetFileName(name);
//open a stream to the zip entry
Stream stream = entry.Open();
//copy stream to memory
MemoryStream memoryStream = new MemoryStream();
stream.CopyTo(memoryStream); //big memory usage?
memoryStream.Position = 0;
return this.File(memoryStream, "application/octet-stream", baseName);
}
}
如果有很多同時下載,這將需要大量 RAM,因此我想直接從存檔中提供它,我知道在解壓縮時需要 CPU,但這很好,因為無論如何下載速度都會非常有限.
我嘗試stream直接提供服務,但出現以下錯誤:
NotSupportedException: Stream does not support reading.
如何直接提供入口流?
uj5u.com熱心網友回復:
問題是既FileStream fs和ZipArchive zip這里設定,所以當它的時間來寫回應和asp.net嘗試讀取您的壓縮條目(stream)-這是不提供任何更多,因為一切都已經布置。
您不需要立即處理它們,而是告訴 asp.net 在完成回應寫入后處理它們。為此,HttpResponsehas method RegisterForDispose,所以你需要做這樣的事情:
string zipFile = @"C:\tmp\record.zip";
FileStream fs = null;
ZipArchive zip = null;
Stream stream = null;
try {
fs = new FileStream(zipFile, FileMode.Open);
zip = new ZipArchive(fs);
ZipArchiveEntry entry = zip.Entries.First(x => x.FullName == "24fa535b-2fc9-4ce5-96f4-2ff1ef0d9b64.json");
string name = entry.FullName;
string baseName = Path.GetFileName(name);
//open a stream to the zip entry
stream = entry.Open();
return this.File(stream, "application/octet-stream", baseName);
}
finally {
if (stream != null)
this.Response.RegisterForDispose(stream);
if (zip != null)
this.Response.RegisterForDispose(zip);
if (fs != null)
this.Response.RegisterForDispose(fs);
}
現在asp.net 將首先寫出回應,然后為您處理所有的一次性用品。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/341137.html
標籤:C# asp.net-mvc
上一篇:我該如何解決這個錯誤?找不到型別或命名空間名稱“EditCourseLevel”(您是否缺少using指令或程式集參考?
