private string ProcessPicture(Member tblMember, HttpPostedFileBase file) { string resultMessage = ""; if (file != null) { string _path = ""; string _serverPath = Server.MapPath("~/Content/Images/members/profilepics"); string _fileName = Path.GetFileName(file.FileName); string _fileExt = _fileName.Substring(_fileName.Length - 4); //from http://www.codeproject.com/Tips/481015/Rename-Resize-Upload-Image-ASP-NET-MVC ImageUpload imageUpload = new ImageUpload { Width = 600 }; //set Width here ImageResult imageResult = imageUpload.RenameUploadFile(file); if (imageResult.Success) { //TODO: write the filename to the db //save path for image to membermedia in db MemberMedia mm = new MemberMedia(); mm.MemberID = tblMember.MemberID; _path = "/Content/Images/members/profilepics/" + imageResult.ImageName; mm.Path = _path; int countExistingMM = db.MemberMedias.Where(m => m.MemberID == tblMember.MemberID).Count(); if (countExistingMM == 0) { mm.PrimaryPic = true; } tblMember.MemberMedias.Add(mm); resultMessage = "Successfully Uploaded Image"; } else { // use imageResult.ErrorMessage to show the error resultMessage = "Successfully Uploaded Image"; } db.SaveChanges(); } return(resultMessage); }
private ImageResult UploadFile(HttpPostedFileBase file, string fileName) { ImageResult imageResult = new ImageResult { Success = true, ErrorMessage = null }; var path = Path.Combine(HttpContext.Current.Request.MapPath(UploadPath), fileName); string extension = Path.GetExtension(file.FileName); //make sure the file is valid if (!ValidateExtension(extension)) { imageResult.Success = false; imageResult.ErrorMessage = "Invalid Extension"; return(imageResult); } try { file.SaveAs(path); Image imgOriginal = Image.FromFile(path); //pass in whatever value you want Image imgActual = Scale(imgOriginal); imgOriginal.Dispose(); imgActual.Save(path); imgActual.Dispose(); imageResult.ImageName = fileName; return(imageResult); } catch (Exception ex) { // you might NOT want to show the exception error for the user // this is generally logging or testing imageResult.Success = false; imageResult.ErrorMessage = ex.Message; return(imageResult); } }