/// <summary> /// Store uploaded file into project database as binary string /// </summary> /// <param name="upload"> Uploaded file </param> /// <returns></returns> public static MFile StoreIntoDatabase(HttpPostedFileBase upload) { var avatar = new MFile { FileName = System.IO.Path.GetFileName(upload.FileName), FileType = FileType.Avatar, ContentType = upload.ContentType }; using (var renderer = new System.IO.BinaryReader(upload.InputStream)) { avatar.Content = renderer.ReadBytes(upload.ContentLength); } return(avatar); }
public ActionResult Create([Bind(Include = "ID,Title,ReleaseDate,Genre,Price,Rating")] Movie movie, HttpPostedFileBase upload) { if (ModelState.IsValid) { db.Movies.Add(movie); db.SaveChanges(); if (upload != null && upload.ContentLength > 0) { var posterImage = new File { // rename before storing FileName = Guid.NewGuid() + Path.GetExtension(upload.FileName), FileType = FileType.Poster, ContentType = upload.ContentType, }; //Should move away from hardcoding path against model since Filename will be enough to find relative path string filePath = string.Format("~/Content/public/{0}/{1}", movie.ID, posterImage.FileName); posterImage.FilePath = filePath; string fileStreamPath = Server.MapPath(filePath); string directoryPath = Server.MapPath("~/Content/public/" + movie.ID + "/"); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } //save to disk using (var fileStream = System.IO.File.Create(fileStreamPath)) { upload.InputStream.Seek(0, SeekOrigin.Begin); upload.InputStream.CopyTo(fileStream); } movie.Images = new List<File> { posterImage }; } db.SaveChanges(); return RedirectToAction("Index"); } return View(movie); }