public ActionResult UploadFile(LgProtocolFileViewModel viewModel) { HttpPostedFileBase file = viewModel.File; //checks if the file contains anything. if (file.ContentLength > 0) { string md5Hash; using (var md5 = MD5.Create()) { //Converts the md5hash to a string without "-". md5Hash = BitConverter.ToString(md5.ComputeHash(file.InputStream)).Replace("-", "").ToLower(); } var uploadDate = DateTime.Now; //Creates the name by concatenating the md5hash with the current date without "-". string nameOnServer = md5Hash + uploadDate.ToString("d").Replace("-", ""); //Converts the relative filepath to the absolute filepath. string filePath = Path.Combine(Server.MapPath("~/App_Data/LgProtocols"), nameOnServer); //Creates a model with info about the file that will later be saved to the database. var model = new LgProtocolModel { Name = Path.GetFileNameWithoutExtension(file.FileName), FileSize = file.ContentLength / 1024, MD5Hash = md5Hash, NameOnServer = nameOnServer, UploadDate = uploadDate }; //Saves the info to the database if it isn't uploaded allready. if (!System.IO.File.Exists(filePath)) { using (IProtocolRepository repository = new ProtocolRepository()) { repository.AddLgProtocol(model); repository.Save(); } //Saves the file to the server. file.SaveAs(filePath); } return Json(new { success = true }, JsonRequestBehavior.AllowGet); } //if the file was empty an error is returned. return Json(new { ErrorMessage = "File was empty" }, JsonRequestBehavior.AllowGet); }
/// <summary> /// Adds info about a meeting protocol to the database. /// </summary> /// <param name="model">The instance of <c>LgProtocolModel</c> representing the info to add.</param> public void AddLgProtocol(LgProtocolModel model) { context.LgProtocols.Add(model); }