Tôi đang cố gắng trả về các tệp lớn thông qua bộ điều khiển ActionResult và đã triển khai lớp FileResult tùy chỉnh như sau.FileResult đệm vào bộ nhớ
public class StreamedFileResult : FileResult
{
private string _FilePath;
public StreamedFileResult(string filePath, string contentType)
: base(contentType)
{
_FilePath = filePath;
}
protected override void WriteFile(System.Web.HttpResponseBase response)
{
using (FileStream fs = new FileStream(_FilePath, FileMode.Open, FileAccess.Read))
{
int bufferLength = 65536;
byte[] buffer = new byte[bufferLength];
int bytesRead = 0;
while (true)
{
bytesRead = fs.Read(buffer, 0, bufferLength);
if (bytesRead == 0)
{
break;
}
response.OutputStream.Write(buffer, 0, bytesRead);
}
}
}
}
Tuy nhiên, vấn đề tôi gặp phải là toàn bộ tệp xuất hiện được lưu vào bộ nhớ. Tôi cần phải làm gì để ngăn chặn điều này?
Tại sao bạn không sử dụng FileStreamResult hiện tại? –
Ban đầu tôi đã thử sử dụng FileStreamResult nhưng nó cũng đệm tệp vào bộ nhớ. –