I want to implement service where by uploading file more than 5 MB it will show a message that the file is too big. Until now it works with file format and name length, but somehow it doesn't work with file size. Can somebody tell me what I'm doing wrong here:
Here is my controller:
[HttpPost]
public JsonResult UpdateJsionFile(int? id, HttpPostedFileBase file)
{
byte[] bytes;
//decimal fileSize = 100;
var supportedTypes = new[] { "txt","doc","docx","pdf", "xls", "xlsx", "png" };
var fileExt = System.IO.Path.GetExtension(file.FileName).ToLower().Substring(1);
var maxSize = 5 * 1024 * 1024;
using (BinaryReader br = new BinaryReader(file.InputStream))
{
bytes = br.ReadBytes(file.ContentLength);
}
if(!supportedTypes.Contains(fileExt))
{
return Json(new { success = false, error = "File extention is invalid - upload only WORD/PDF/EXCEL/TXT/PNG files" }, JsonRequestBehavior.AllowGet);
}
if(file.FileName.Length>50 )
{
return Json(new { success = false, error = "File name is too long, max. 50 symbols" }, JsonRequestBehavior.AllowGet);
}
if (file.ContentLength > maxSize)
{
return Json(new { success = false, error = "File size is too big, max 5MB" }, JsonRequestBehavior.AllowGet);
}
using (FileDBEntities db = new FileDBEntities())
{
tblFile f = db.tblFiles.Where(p => p.id == id).FirstOrDefault();
f.Name = Path.GetFileName(file.FileName);
f.ContentType = file.ContentType;
f.Data = bytes;
db.SaveChanges();
}
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}