我需要上传潜在的大文件到我们的网站,然后到数据库中。但是,每次我实例化存储文件数据的byte []时,都会立即得到System.OutOfMemoryException。该框具有足够的内存,但IIS/.Net似乎对进程内存有限制。MVC5上传大文件到DB System.OutOfMemoryException
型号:
public class CreateFileModel : IFileModel {
...
[ScaffoldColumn(false)]
public byte[] FileData { get; set; }
...
}
POST操作:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateFile(CreateFileModel model) {
try {
if (ModelState.IsValid && Request != null && Request.Files.Count > 0) {
foreach (string uploadname in Request.Files) {
HttpPostedFileBase uploadedFile = Request.Files[uploadname];
if (uploadedFile?.ContentLength > 0) {
model.FileData = new byte[uploadedFile.ContentLength]; // <-- BREAKS HERE WITH OutOfMemoryException
uploadedFile.InputStream.Read(model.FileData, 0, Convert.ToInt32(uploadedFile.ContentLength));
}
}
if (model.FileData.Length > 0) {
FileMapper mapper = new FileMapper();
mapper.Create(model);
return RedirectToAction("Index", "Index", new { pucoId = CurrentUser.PUCOID, folderId = CurrentDirectoryId });
}
}
}
catch (Exception ex) {
OnError(ex);
}
model.FileData = null;
return View(model);
}
}
错误实例化的模型,该模型将被用于更新数据库接收缓冲区时,总是会发生的。
model.FileData = new byte[uploadedFile.ContentLength];
所以我想弄清楚从哪里去。我可以使用较小的缓冲区将文件保存到文件系统,但是我实际上永远无法将它们存入数据库。
你会如何解决这个问题?
是不好的做法,直接上传文件到数据库。相反,保存到一个文件夹并将路径添加到您的数据库。 –
这将涉及重写应用程序的大块,事实上,维护与数据链接的大型文件层次结构是不鼓励的,因为维护数据库和文件系统中数据的完整性是一项重要任务。 –