簡體   English   中英

上傳大文件時拋出'System.OutOfMemoryException'

[英]'System.OutOfMemoryException' was thrown while uploading large file

當我上傳大於500 MB的文件時,我收到以下錯誤

“拋出了'System.OutOfMemoryException'類型的異常。”

我的代碼如下所示:

public readonly string Filename, ContentType;
public readonly int Size;
public readonly byte[] Bytes;

public FileHolder(HttpPostedFile file)
{
            Filename = Path.GetFileName(file.FileName);
            ContentType = GetContentType(file.ContentType, Filename);
            Size = file.ContentLength;
            Bytes = new byte[file.InputStream.Length];          //Here i get error
            file.InputStream.Read(Bytes, 0, Size);
}

不要試圖一次讀取整個流。 無論如何,你不會同時獲得整個流。

創建一個合理大小的緩沖區,然后一次讀取一個塊:

byte[] buffer = new byte[8192];
int offset = 0;
int left = Size;
while (left > 0) {
  int len = file.InputStream.Read(buffer, 0, Math.Min(buffer.Length, left));
  left -= len;
  // here you should store the first "len" bytes of the buffer
  offset += len;
}

您不應將整個文件加載到字節數組中。 相反,您可以直接從輸入流處理文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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