简体   繁体   中英

'System.OutOfMemoryException' was thrown while uploading large file

I get following error when i upload files larger than 500 MB

"Exception of type 'System.OutOfMemoryException' was thrown. "

My code is shown below:

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);
}

Don't try to read the entire stream all at once. You won't get the entire stream all at once anyway.

Create a buffer with a reasonable size, then read a block at a time:

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;
}

You should not load the entire file into a byte array. Instead, you can process the file directly from the input stream.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM