Reputation: 7879
I'm getting this error when uploading a file that is 84MB (see error below) but when I upload a ~60MB file, it works fine. This only occurs on our 32bit 2008 VM w/ 4GB memory. On my R2 64bit VM w/8GB memory, it works fine with even 130MB file.
System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown. at System.IO.BinaryReader.ReadBytes(Int32 count) at CustWeb.Controllers.DownloadsController.Create(Download dl, HttpPostedFileBase file) in c:\...\CustWeb\Controllers\DownloadsController.cs:line 72
I monitored the Memory in the task manager, though, and it never goes above 74% during the entire upload process.
This is an MVC 4 application on the 4.5 .NET framework.
I have the max settings in my web.config in dealing with uploading files.
<httpRuntime requestValidationMode="4.5" targetFramework="4.5" maxRequestLength="2147483647" executionTimeout="84000" />
...
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="2147482624" />
</requestFiltering>
</security>
UPDATE Adding code as requested:
public ActionResult Create(Download dl, HttpPostedFileBase file)
{
try
{
using (var binaryReader = new BinaryReader(file.InputStream))
{
dl.FileBytes = binaryReader.ReadBytes(file.ContentLength);
}
dl.FileContentType = file.ContentType;
dl.FileName = file.FileName;
dl.Insert();
Success("<strong>" + dl.Label + "</strong> created and uploaded successfully.");
return RedirectToAction("Index");
}
catch (Exception ex)
{
SelectList list = new SelectList(new DownloadType().GetDownloadTypes(), "ID", "Name");
ViewBag.DownloadTypeList = list;
Error(ex.ToString());
return View(dl);
}
}
Upvotes: 3
Views: 7927
Reputation: 7879
I changed it from stream to file.SaveAs and that prevented the memory error.
public ActionResult Create(Download dl, HttpPostedFileBase file)
{
try
{
string tempFile = Path.Combine(Server.MapPath("~/App_Data/"), string.Format("{0}_{1}",Guid.NewGuid().ToString(), Path.GetFileName(file.FileName)));
file.SaveAs(tempFile);
dl.FileBytes = System.IO.File.ReadAllBytes(tempFile);
dl.FileContentType = file.ContentType;
dl.FileName = file.FileName;
dl.Insert();
System.IO.File.Delete(tempFile);
Success("<strong>" + dl.Label + "</strong> created and uploaded successfully.");
return RedirectToAction("Index");
}
catch (Exception ex)
{
SelectList list = new SelectList(new DownloadType().GetDownloadTypes(), "ID", "Name");
ViewBag.DownloadTypeList = list;
Error(ex.ToString());
return View(dl);
}
}
Upvotes: 0
Reputation: 39777
By default ASP.NET is allowed 60% of available memory - check memoryLimit in processModel in machine.config. You can change that value to, say 80% to give ASP.NET more room, but this is not recommend. Consider other options, like uploading file in chunks etc.
Upvotes: 3