public ActionResult Create(CreateProductPostRequest productRequest) { productRequest.CreateBy = User.Identity.GetUserName(); if (User.IsInRole("Administrator")) { productRequest.Status = (int)Define.Status.Active; } else { productRequest.Status = (int)Define.Status.WaitingCreate; } if (ModelState.IsValid) { var file = Request.Files["coverImage"]; //HttpPostedFileBase file = coverImage; if (file != null && file.ContentLength > 0) { if (file.ContentLength > 0) { // width + height will force size, care for distortion //Exmaple: ImageUpload imageUpload = new ImageUpload { Width = 800, Height = 700 }; // height will increase the width proportionally //Example: ImageUpload imageUpload = new ImageUpload { Height= 600 }; // width will increase the height proportionally ImageUpload imageUpload = new ImageUpload { Width = 600 }; // rename, resize, and upload //return object that contains {bool Success,string ErrorMessage,string ImageName} ImageResult imageResult = imageUpload.RenameUploadFile(file); if (imageResult.Success) { // Add new image to database var photo = new share_Images { ImageName = imageResult.ImageName, ImagePath = Path.Combine(ImageUpload.LoadPath, imageResult.ImageName) }; var imageId = service.AddImage(photo); // Add product productRequest.CoverImageId = imageId; productRequest.CreateBy = User.Identity.GetUserName(); service.AddProduct(productRequest); return(RedirectToAction("Index")); } else { // use imageResult.ErrorMessage to show the error ViewBag.Error = imageResult.ErrorMessage; } } } } PopulateStatusDropDownList(); ViewBag.BrandId = PopulateListBrand(productRequest.BrandId); return(View("Create1", productRequest)); }
public ActionResult Create(CMSNewsView model, HttpPostedFileBase uploadFile) { if (ModelState.IsValid) { try { if (User.IsInRole("Administrator")) { model.Status = (int)OnlineStore.Infractructure.Utility.Define.Status.Active; } else { model.Status = (int)OnlineStore.Infractructure.Utility.Define.Status.WaitingCreate; } if (uploadFile != null && uploadFile.ContentLength > 0) { ImageUpload imageUpload = new ImageUpload { IsScale = false, SavePath = ImageUpload.LoadPathCMSNews }; ImageResult imageResult = imageUpload.RenameUploadFile(uploadFile); if (imageResult.Success) { // Add new image to database var photo = new share_Images { ImageName = imageResult.ImageName, ImagePath = imageResult.ImagePath }; var imageId = _productService.AddImage(photo); if (imageId != null) { // Add banner model.CoverImageId = imageId.Value; } } else { ViewBag.Error = imageResult.ErrorMessage; } } _cmsNewsService.AddCMSNews(model); return(RedirectToAction("Index")); } catch (Exception ex) { ModelState.AddModelError("", ex.Message); } } ViewBag.AvailableCategories = PrepareAllCategoriesModel(); return(View(model)); }
public ActionResult UploadImage(HttpPostedFileBase upload, string CKEditorFuncNum, string CKEditor, string langCode) { string dfolder = DateTime.Now.Date.ToString("ddMMyyyy"); string url = "/images/media/" + dfolder + "/"; // url to return string message; // message to display (optional) if (upload != null) { string ImageName = upload.FileName; string fsave = "~/images/media/" + dfolder; bool exists = System.IO.Directory.Exists(Server.MapPath(fsave)); if (!exists) { System.IO.Directory.CreateDirectory(Server.MapPath(fsave)); } string path = System.IO.Path.Combine(Server.MapPath(fsave), ImageName); MemoryStream target = new MemoryStream(); upload.InputStream.CopyTo(target); byte[] data = target.ToArray(); ImageUpload imageUpload = new ImageUpload { Width = 800, isSacle = false, UploadPath = fsave }; ImageResult imageResult = imageUpload.RenameUploadFile(data, Path.GetExtension(upload.FileName)); if (imageResult.Success) { message = "Đả tải"; url = url + imageResult.ImageName; } else { message = ""; url = ""; } } else { message = ""; url = ""; } string output = @"<html><body><script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"" + url + "\", \"" + message + "\");</script></body></html>"; return(Content(output)); }
public async Task <ActionResult> Create([Bind(Include = "DepartmentID,Name,Budget,StartDate,InstructorID")] Department department, HttpPostedFileBase ImageName) { ViewBag.InstructorID = new SelectList(db.Instructors, "ID", "LastName", department.InstructorID); if (ModelState.IsValid) { //pbrooker: added image upload //Note the HttpPostedFileBase args in the method //Also the from needs a enctype="multipart/form-data" //and <input type="file" id="ImageName" name="ImageName" accept="image/*" class = "form-control"/> if (ImageName != null && ImageName.ContentLength > 0) { //do we have anything to upload - yes var validImageTypes = new string[] { //"image/gif", //"image/jpg", //"iamge/jpeg", "image/png" }; if (!validImageTypes.Contains(ImageName.ContentType)) { //file being uploaded is not a png - display error ModelState.AddModelError("", "Please chose a PNG image."); return(View(department)); } //save new department to database db.Departments.Add(department); await db.SaveChangesAsync(); //Retreive the IDENTITY from SQL Server string pictureName = department.DepartmentID.ToString(); //rename, scale and upload image ImageUpload imageUpload = new ImageUpload { Width = 128 }; ImageResult imageResult = imageUpload.RenameUploadFile(ImageName, pictureName); return(RedirectToAction("Index")); } else { //nothing to upload - display error ModelState.AddModelError("", "YOu have not selected an image file to upload."); return(View(department)); } } return(View(department)); }
public ActionResult UploadCover(FormCollection formCollection, HttpPostedFileBase imagefile) { int id = Convert.ToInt32(formCollection["BookID"]); if (id == -1) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Book book = _db.Query <Book>().FirstOrDefault(b => b.BookID == id); if (book == null) { return(HttpNotFound()); } if (imagefile.ContentLength > 0) { // width + height will force size, care for distortion //Exmaple: ImageUpload imageUpload = new ImageUpload { Width = 800, Height = 700 }; // height will increase the width proportionally //Example: ImageUpload imageUpload = new ImageUpload { Height= 600 }; // width will increase the height proportionally ImageUpload imageUpload = new ImageUpload { Width = 300 }; // rename, resize, and upload //return object that contains {bool Success,string ErrorMessage,string ImageName} ImageResult imageResult = imageUpload.RenameUploadFile(imagefile); if (imageResult.Success) { book.ImageUrl = imageResult.ImageName; _db.Update(book); _db.SaveChanges(); TempData["book"] = book; return(RedirectToAction("UploadCompleted")); } else { // use imageResult.ErrorMessage to show the error ViewBag.Error = imageResult.ErrorMessage; } } return(View()); }
public ActionResult Create(CreateProjectPostRequest projectRequest) { if (ModelState.IsValid) { var file = Request.Files["coverImage"]; if (file != null && file.ContentLength > 0) { if (file.ContentLength > 0) { // width + height will force size, care for distortion //Exmaple: ImageUpload imageUpload = new ImageUpload { Width = 800, Height = 700 }; // height will increase the width proportionally //Example: ImageUpload imageUpload = new ImageUpload { Height= 600 }; // width will increase the height proportionally ImageUpload imageUpload = new ImageUpload { Width = 600 }; // rename, resize, and upload //return object that contains {bool Success,string ErrorMessage,string ImageName} ImageResult imageResult = imageUpload.RenameUploadFile(file); if (imageResult.Success) { // Add new image to database var photo = new share_Images { ImageName = imageResult.ImageName, ImagePath = Path.Combine(ImageUpload.LoadPath, imageResult.ImageName) }; var imageId = service.AddImage(photo); // Add product projectRequest.CoverImageId = imageId; service.AddProject(projectRequest); return(RedirectToAction("Index")); } else { // use imageResult.ErrorMessage to show the error ViewBag.Error = imageResult.ErrorMessage; } } } } PopulateProjectTypeDropDownList(); PopulateRegionDropDownList(); PopulateProgressStatusDropDownList(); PopulateStatusDropDownList(); return(View(projectRequest)); }
public async Task <ActionResult> Create(Moto moto, HttpPostedFileBase FotoMoto, String fkRole) { CAUsuario usuario; if (Session["usuario"] == null) { return(RedirectToAction("Login", "CAUsuarios", new { urlRetorno = Request.Url.AbsolutePath })); } else { usuario = (CAUsuario)Session["usuario"]; } moto.fkUsuario = usuario.pkUsuario; if (ModelState.IsValid) { ImageUpload imageUpload = new ImageUpload { Width = 800 }; if (FotoMoto != null && FotoMoto.FileName != null) { ImageResult imageResult = imageUpload.RenameUploadFile(FotoMoto); if (!imageResult.Success) { ModelState.AddModelError("FotoMoto", "Ocorreu um erro no Envio de Foto, Verifique o Arquivo."); return(View()); } else { moto.foto = imageResult.ImageName; } } db.Moto.Add(moto); await db.SaveChangesAsync(); if (fkRole != null) { return(RedirectToAction("Details", "Roles", new { id = fkRole })); } return(RedirectToAction("Index")); } ViewBag.fkMarca = new SelectList(db.Marca, "pkMarca", "DescricaoMarca", moto.fkMarca); return(View(moto)); }
public ActionResult Edit(CMSNewsView model, HttpPostedFileBase uploadFile) { if (ModelState.IsValid) { try { if (uploadFile != null && uploadFile.ContentLength > 0) { ImageUpload imageUpload = new ImageUpload { IsScale = false, SavePath = ImageUpload.LoadPathCMSNews }; ImageResult imageResult = imageUpload.RenameUploadFile(uploadFile); if (imageResult.Success) { // Add new image to database var photo = new share_Images { ImageName = imageResult.ImageName, ImagePath = imageResult.ImagePath }; //var imageId = _productService.AddImage(photo); //if (imageId != null) //{ // // Add banner // model.CoverImageId = imageId.Value; //} } else { ViewBag.Error = imageResult.ErrorMessage; } } _cmsNewsService.EditCMSNews(model); return(RedirectToAction("Index")); } catch (Exception ex) { ModelState.AddModelError("", ex.Message); } } ViewBag.AvailableCategories = PrepareAllCategoriesModel(model.Id); PopulateStatusDropDownList((Portal.Infractructure.Utility.Define.Status)model.Status); return(View(model)); }
public ActionResult UploadImage(HttpPostedFileBase image, string extension, string user, string token, int folder) { if (mongoHelp.checkLoginSession(user, token)) { string folderSave = FolderSave(folder); string fsave = "~/uploadfolder/" + folderSave; bool exists = System.IO.Directory.Exists(Server.MapPath(fsave)); if (!exists) { System.IO.Directory.CreateDirectory(Server.MapPath(fsave)); } string urlThumbnail = ""; try { MemoryStream target = new MemoryStream(); image.InputStream.CopyTo(target); byte[] data = target.ToArray(); ImageUpload imageUpload = new ImageUpload { Width = 3000, isSacle = false, UploadPath = fsave, user = user }; ImageResult imageResult = imageUpload.RenameUploadFile(data, extension); if (imageResult.Success) { urlThumbnail = "/uploadfolder/" + folderSave + "/" + imageResult.ImageName; } } catch { return(Json(new { id = "0", msg = "Image upload to fail" }, JsonRequestBehavior.AllowGet)); } return(Json(new { id = "1", msg = urlThumbnail }, JsonRequestBehavior.AllowGet)); } return(Json(new { id = "0", msg = "Faile token user" }, JsonRequestBehavior.AllowGet)); }
public async Task <ActionResult> Create([Bind(Include = "DepartmentID,Name,Budget,StartDate,InstructorID")] Department department, HttpPostedFileBase ImageName) { ViewBag.InstructorID = new SelectList(db.Instructors, "ID", "LastName", department.InstructorID); if (ModelState.IsValid) { //mwilliams: added image upload //Note the HttpPostedFileBase ImageName args in method //Also the form needs a enctype="multipart/form-data" // And <input type="file" id="ImageName" name="ImageName" accept="image/*" class="form-control" /> if (ImageName != null && ImageName.ContentLength > 0) { var validImageTypes = new string[] { //"image/gif", //"image/jpg", //"image/jpeg", "image/png" }; if (!validImageTypes.Contains(ImageName.ContentType)) { ModelState.AddModelError("", "Please choose a PNG image"); return(View(department)); } db.Departments.Add(department); await db.SaveChangesAsync(); string pictureName = department.DepartmentID.ToString(); ImageUpload imageUpload = new ImageUpload { Width = 128 }; ImageResult imageResult = imageUpload.RenameUploadFile(ImageName, pictureName); return(RedirectToAction("Index")); } else { ModelState.AddModelError("", "You have not selected and image file to upload"); return(View(department)); } } return(View(department)); }
public ActionResult Edit(BannerViewModel model, HttpPostedFileBase uploadFile) { if (ModelState.IsValid) { if (uploadFile != null && uploadFile.ContentLength > 0) { ImageUpload imageUpload = new ImageUpload { IsScale = false, SavePath = ImageUpload.LoadPathBanners }; ImageResult imageResult = imageUpload.RenameUploadFile(uploadFile); if (imageResult.Success) { // Add new image to database var photo = new share_Images { ImageName = imageResult.ImageName, ImagePath = imageResult.ImagePath }; //var imageId = _productService.AddImage(photo); //if (imageId != null) //{ // // Add banner // model.ImageId = imageId.Value; //} } else { ViewBag.Error = imageResult.ErrorMessage; } } _bannerService.EditBanner(model); return(RedirectToAction("Index")); } PopulateBannerTypesDropDownList((Portal.Infractructure.Utility.Define.BannerTypes)model.Type); PopulateStatusDropDownList((Portal.Infractructure.Utility.Define.Status)model.Status); return(View(model)); }
private string UploadSinglePhoto(HttpPostedFileBase file) { if (file.ContentLength <= 0) { return("#fail_" + file.FileName); } var imageUpload = new ImageUpload { Width = FapConstants.UploadedImageMaxWidthPixcel, Height = FapConstants.UploadedImageMaxHeightPixcel }; var imageResult = imageUpload.RenameUploadFile(file); if (imageResult.Success) { return(imageResult.ImageName); } return("#fail_" + imageResult.ImageName); }
public ActionResult Edit(Service aService, HttpPostedFileBase file) { if (file != null) { var fileName = Path.GetFileName(file.FileName); ImageUpload imageUploadOriginal = new ImageUpload { Image_Prepend = "org_" }; // rename, resize, and upload //return object that contains {bool Success,string ErrorMessage,string ImageName} ImageResult imageResultOriginal = imageUploadOriginal.RenameUploadFile(file); //thumb Image ImageUpload imageUploadThumb = new ImageUpload { Width = 150, Height = 100, Image_Prepend = "thumb_" }; // rename, resize, and upload //return object that contains {bool Success,string ErrorMessage,string ImageName} ImageResult imageResultThumb = imageUploadThumb.RenameUploadFile(file); //Image Mid ImageUpload imageUploadMid = new ImageUpload { Height = 400, Width = 600, Image_Prepend = "mid_" }; // rename, resize, and upload //return object that contains {bool Success,string ErrorMessage,string ImageName} ImageResult imageResultMid = imageUploadMid.RenameUploadFile(file); aService.ImageOriginal = imageResultOriginal.ImageName; aService.ImageThumb = imageResultThumb.ImageName; aService.ImageMid = imageResultMid.ImageName; } context.services.Attach(aService); context.Entry(aService).State = EntityState.Modified; context.SaveChanges(); return(RedirectToAction("Index", context.services.ToList())); }
public ActionResult Create(BannerViewModel model, HttpPostedFileBase uploadFile) { if (ModelState.IsValid) { if (uploadFile != null && uploadFile.ContentLength > 0) { ImageUpload imageUpload = new ImageUpload { IsScale = false, SavePath = ImageUpload.LoadPathBanners }; ImageResult imageResult = imageUpload.RenameUploadFile(uploadFile); if (imageResult.Success) { // Add new image to database var photo = new share_Images { ImageName = imageResult.ImageName, ImagePath = imageResult.ImagePath }; var imageId = _productService.AddImage(photo); if (imageId != null) { // Add banner model.ImageId = imageId.Value; _bannerService.AddBanner(model); return(RedirectToAction("Index")); } } else { ViewBag.Error = imageResult.ErrorMessage; } } } PopulateBannerTypesDropDownList(); return(View(model)); }
public async Task <ActionResult> Create([Bind(Include = "DepartmentID,Name,Budget,StartDate,InstructorID")] Department department, HttpPostedFileBase ImageName) { ViewBag.InstructorID = new SelectList(db.Instructors, "ID", "LastName", department.InstructorID); if (ModelState.IsValid) { //add himage upload //note the ImageName args in method if (ImageName != null && ImageName.ContentLength > 0) { var validImageTypes = new string[] { /*"image/gif", "image/jpg", "image/jpeg", */ "image/png" }; if (!validImageTypes.Contains(ImageName.ContentType)) { ModelState.AddModelError("", "Uploaded file not valid format."); return(View(department)); } db.Departments.Add(department); await db.SaveChangesAsync(); //Retrieve ID for naming string pictureName = department.DepartmentID.ToString(); //Rename, Scale, Upload ImageUpload imageUpload = new ImageUpload { Width = 128 }; ImageResult imageResult = imageUpload.RenameUploadFile(ImageName, pictureName); return(RedirectToAction("Index")); } else { ModelState.AddModelError("", "Problem with file. Try again."); return(View(department)); } } return(View(department)); }
public async Task <ActionResult> MeusDados(FormularioUsuarios form, HttpPostedFileBase FotoPerfil) { try { CAUsuario usuario; if (Session["usuario"] == null) { RedirectToAction("Login", "CAUsuarios"); return(View()); } else { usuario = (CAUsuario)Session["usuario"]; } if (form.usuario.nome == null) { ModelState.AddModelError("usuario.nome", "Digite seu nome!"); } else { usuario.nome = form.usuario.nome; } if (form.usuario.apelido == null) { ModelState.AddModelError("usuario.apelido", "Digite seu apelido!"); } else { usuario.apelido = form.usuario.apelido; } usuario.fone = form.usuario.fone; if (form.usuario.senha != null) { if (form.usuario.senha.Equals(form.senhaConfirmacao)) { usuario.senha = funcoesUteis.Criptografar(form.usuario.senha); } else { ModelState.AddModelError("senhaConfirmacao", "A Senha e Confirmação da Senha não Conferem!"); return(View()); } } if (form.autocomplete == null) { ModelState.AddModelError("autocomplete", "Digite sua Cidade!"); } if (!ModelState.IsValid) { return(View()); } LocalidadesController loc = new LocalidadesController(); usuario.fkLocalidade = loc.carregaLocalidadeGoogle(form.administrative_area_level_2, form.country, form.administrative_area_level_1, form.longitude.ToString(), form.latitude.ToString(), form.autocomplete.ToString()); usuario.coordenadas = DbGeography.FromText(string.Format("POINT({0} {1})", form.latitude.Replace(",", "."), form.longitude.Replace(",", ".")), 4326); ImageUpload imageUpload = new ImageUpload { Width = 800 }; if (FotoPerfil != null && FotoPerfil.FileName != null) { ImageResult imageResult = imageUpload.RenameUploadFile(FotoPerfil); if (!imageResult.Success) { ModelState.AddModelError("usuario.foto", "Ocorreu um erro no Envio de Foto, Verifique o Arquivo."); return(View()); } else { usuario.foto = imageResult.ImageName; } } db.Entry(usuario).State = EntityState.Modified; await db.SaveChangesAsync(); return(RedirectToAction("IndexInterno", "Home")); } catch (Exception er) { ViewBag.administrative_area_level_2 = form.administrative_area_level_2; ViewBag.administrative_area_level_1 = form.administrative_area_level_1; ViewBag.country = form.country; ViewBag.autocomplete = form.autocomplete; ViewBag.longitude = form.longitude; ViewBag.latitude = form.latitude; ViewBag.Erro = er.Message.ToString(); return(View()); } return(View()); }
public ActionResult Create(Package package, HttpPostedFileBase TImage, ICollection <HttpPostedFileBase> AImage) { if (ModelState.IsValid) { foreach (var file in AImage) { if (file != null && file.ContentLength > 0) { imgesUpload = new ImageUpload { Width = 200 }; ImageResult imageResult = imgesUpload.RenameUploadFile(file); fileDetails.Add(imgesUpload.fileDetails); } } package.PImage = fileDetails; package.CreatedBy = Session["userEmail"].ToString(); package.CreatedDate = DateTime.Now; db.packages.Add(package); db.SaveChanges(); db.Entry(package).GetDatabaseValues(); string body; using (var sr = new StreamReader(Server.MapPath("\\App_Data\\HtmlTamplate\\PackageTemplate.html"))) { body = sr.ReadToEnd(); } var charts = db.pImages.Where(m => m.PackageId == package.Id); string category = Session["ACategory"].ToString(); var costumer = db.customers.Where(t => t.category == category).Select(t => t.email1).ToList(); var rate = db.customers.Where(t => t.category == category).Select(t => t.CustomerCategory).ToList(); try { using (var smtp = new SmtpClient()) { for (int i = 0; i < costumer.Count; i++) { var message = new MailMessage(); message.To.Add(new MailAddress(costumer[i])); string email = costumer[i]; var name = db.customers.FirstOrDefault(t => t.category == category && t.email1 == email).Firstname; var image = package.thumbnail; string Packagenamename = package.PackageName; string costumername = Convert.ToString(name); string From = package.From; string to = package.TO; string startdate = package.BegainDate.ToString(); DateTime endtime = Convert.ToDateTime(startdate).AddDays(package.Duration); string time = endtime.ToShortDateString(); decimal rate1; if (rate[i] == "Wholesale") { rate1 = package.Rate1; } else { rate1 = package.Rate2; } string messageBody = string.Format(body, Packagenamename, costumername, startdate, time, From, to, rate1); //int k = 0; //foreach (var item in charts) //{ // string path = Server.MapPath(item.ImageName); // my logo is placed in images folder string path = Server.MapPath(@"/images/dbug.gif"); // my logo is placed in images folder // string messageBody = string.Format(body, username, username, ticketdate, tickettime); AlternateView avHtml = AlternateView.CreateAlternateViewFromString(messageBody, null, MediaTypeNames.Text.Html); LinkedResource logo = new LinkedResource(path, MediaTypeNames.Image.Jpeg); // logo.ContentId = Convert.ToString(k); avHtml.LinkedResources.Add(logo); message.AlternateViews.Add(avHtml); logo.ContentId = "logo"; // k++; // } // avHtml.LinkedResources.Add(logo); message.Subject = "New Package Has Been Added"; message.Body = messageBody; message.IsBodyHtml = true; smtp.Send(message); } } } catch { return(RedirectToAction("Error")); } if (TImage != null) { string fileName3 = TImage.FileName; string firstpath = "/images/"; string subPath = "/images/Thumbail/"; // your code goes here string ppath = "/images/Thumbail/Package/"; bool imageexist = System.IO.Directory.Exists(Server.MapPath(firstpath)); bool exists = System.IO.Directory.Exists(Server.MapPath(subPath)); bool ppp = System.IO.Directory.Exists(Server.MapPath(ppath)); if (!imageexist) { System.IO.Directory.CreateDirectory(Server.MapPath(firstpath)); } if (!exists) { System.IO.Directory.CreateDirectory(Server.MapPath(subPath)); } if (!ppp) { System.IO.Directory.CreateDirectory(Server.MapPath(ppath)); } string filename3 = Path.GetFileNameWithoutExtension(TImage.FileName); string extension3 = Path.GetExtension(TImage.FileName); filename3 = package.Id + extension3; package.thumbnail = "/images/Thumbail/Package/" + filename3; filename3 = Path.Combine(Server.MapPath("~/images/Thumbail/Package/"), filename3); TImage.SaveAs(filename3); } db.packages.Attach(package); db.Entry(package).Property(x => x.thumbnail).IsModified = true; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(package)); }
public ActionResult Decor(HttpPostedFileBase image, string extension, string user, string token, string checkInId, string group) { if (mongoHelp.checkLoginSession(user, token)) { HaiStaff staff = db.HaiStaffs.Where(p => p.UserLogin == user).FirstOrDefault(); if (staff == null) { return(Json(new { id = "0", msg = "Sai thong tin" }, JsonRequestBehavior.AllowGet)); } var cWork = db.CalendarWorks.Find(checkInId); if (cWork == null) { return(Json(new { id = "0", msg = "Sai thong tin" }, JsonRequestBehavior.AllowGet)); } string dfolder = user + "/" + group + "/" + DateTime.Now.Date.ToString("dd-MM-yyyy"); string fsave = "~/uploadfolder/" + dfolder; bool exists = System.IO.Directory.Exists(Server.MapPath(fsave)); if (!exists) { System.IO.Directory.CreateDirectory(Server.MapPath(fsave)); } string urlThumbnail = ""; try { MemoryStream target = new MemoryStream(); image.InputStream.CopyTo(target); byte[] data = target.ToArray(); ImageUpload imageUpload = new ImageUpload { Width = 3000, isSacle = false, UploadPath = fsave, user = cWork.AgencyCode }; ImageResult imageResult = imageUpload.RenameUploadFile(data, extension); if (imageResult.Success) { urlThumbnail = "/uploadfolder/" + dfolder + "/" + imageResult.ImageName; } // save inffo var decor = new DecorImage() { Id = Guid.NewGuid().ToString(), CreateTime = DateTime.Now.TimeOfDay, DecorGroup = group, ImageUrl = urlThumbnail, CalendarWorkID = checkInId }; db.DecorImages.Add(decor); db.SaveChanges(); } catch { return(Json(new { id = "0", msg = "Image upload to fail" }, JsonRequestBehavior.AllowGet)); } return(Json(new { id = "1", msg = urlThumbnail }, JsonRequestBehavior.AllowGet)); } return(Json(new { id = "0", msg = "Faile token user" }, JsonRequestBehavior.AllowGet)); }
public async Task <ActionResult> Create(FormulariosRoles form, HttpPostedFileBase FotoCapa) { try { if (Session["usuario"] == null) { return(RedirectToAction("Login", "CAUsuarios")); } CAUsuario usuario = (CAUsuario)Session["usuario"]; Role role = form.role; role.fkUsuario = usuario.pkUsuario; role.dataHoraCadastro = DateTime.Now; role.fkTipoRole = form.fkTipoRole; if (form.autocomplete == null) { ModelState.AddModelError("autocomplete", "Digite a Cidade"); } if (role.titulo == null) { ModelState.AddModelError("role.titulo", "Digite eo Titulo"); } if (role.descricaoRole == null) { ModelState.AddModelError("role.descricaoRole", "Entre com a Descrição"); } if (role.totalKM == null) { ModelState.AddModelError("role.totalKM", "Digite quantos Kms devem rodar"); } if (role.localPartida == null) { ModelState.AddModelError("role.localPartida", "Qual será o ponto de encontro/partida?"); } DateTime data; if (!DateTime.TryParse(role.dataRole.ToString(), out data)) { ModelState.AddModelError("role.dataRole", "Entre com uma data valida! ex: 20/05/2017"); } if (role.dataRole == null) { ModelState.AddModelError("role.dataRole", "Digite a data! ex: 20/05/2017"); } if (role.horaRole == null) { ModelState.AddModelError("role.horaRole", "Digite a hora! ex: 07:00"); } LocalidadesController loc = new LocalidadesController(); role.fkLocalidade = loc.carregaLocalidadeGoogle(form.administrative_area_level_2, form.country, form.administrative_area_level_1, form.longitude.ToString(), form.latitude.ToString(), form.autocomplete.ToString()); ImageUpload imageUpload = new ImageUpload { Width = 800 }; if (FotoCapa != null && FotoCapa.FileName != null) { ImageResult imageResult = imageUpload.RenameUploadFile(FotoCapa); if (!imageResult.Success) { ModelState.AddModelError("FotoCapa", "Digite a hora! ex: 07:00"); return(View()); } else { role.capa = imageResult.ImageName; } } else { role.capa = "tipo" + role.fkTipoRole.ToString() + ".jpg"; } role.ativo = true; if (ModelState.IsValid) { db.Role.Add(role); await db.SaveChangesAsync(); return(RedirectToAction("Index")); } ViewBag.fkUsuario = new SelectList(db.CAUsuario, "pkUsuario", "nome", role.fkUsuario); ViewBag.fkTipoRole = new SelectList(db.TipoRole, "pkTipoRole", "descricao", role.fkTipoRole); return(View(form)); } catch (Exception er) { ModelState.AddModelError("titulo", er.StackTrace.ToString()); return(View(form)); } return(RedirectToAction("../Roles/Index")); }
public ActionResult Create(Service aService, FormCollection formCollection) { foreach (string item in Request.Files) { HttpPostedFileBase file = Request.Files[item] as HttpPostedFileBase; if (file.ContentLength == 0) { continue; } if (file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); // width + height will force size, care for distortion //Exmaple: ImageUpload imageUpload = new ImageUpload { Width = 800, Height = 700 }; // height will increase the width proportially //Example: ImageUpload imageUpload = new ImageUpload { Height= 600 }; // width will increase the height proportially //Original Image ImageUpload imageUploadOriginal = new ImageUpload { Image_Prepend = "org_" }; // rename, resize, and upload //return object that contains {bool Success,string ErrorMessage,string ImageName} ImageResult imageResultOriginal = imageUploadOriginal.RenameUploadFile(file); //thumb Image ImageUpload imageUploadThumb = new ImageUpload { Width = 150, Height = 100, Image_Prepend = "thumb_" }; // rename, resize, and upload //return object that contains {bool Success,string ErrorMessage,string ImageName} ImageResult imageResultThumb = imageUploadThumb.RenameUploadFile(file); //Image Mid ImageUpload imageUploadMid = new ImageUpload { Height = 400, Width = 600, Image_Prepend = "mid_" }; // rename, resize, and upload //return object that contains {bool Success,string ErrorMessage,string ImageName} ImageResult imageResultMid = imageUploadMid.RenameUploadFile(file); if (imageResultOriginal.Success && imageResultMid.Success && imageResultThumb.Success) { //TODO: write the filename to the db Console.WriteLine(imageResultOriginal.ImageName); aService.ImageOriginal = imageResultOriginal.ImageName; aService.ImageThumb = imageResultThumb.ImageName; aService.ImageMid = imageResultMid.ImageName; if (aService.Detail.Length > 150) { aService.DisplayDetail = aService.Detail.Substring(0, 150); } context.services.Add(aService); context.SaveChanges(); } else { //TODO: show view error // use imageResult.ErrorMessage to show the error ViewBag.Error = imageResultOriginal.ErrorMessage; } } } return(View()); }
public async Task <ActionResult> Create(FormularioUsuarios form, HttpPostedFileBase FotoPerfil) { try { CAUsuario usuario = form.usuario; usuario.fkInstancia = 1; usuario.fkPerfil = 1; if (db.CAUsuario.Where(o => o.email.Equals(form.usuario.email.ToLower())).Any()) { ModelState.Remove("usuario.nome"); ViewBag.msgErro = "Já existe um cadastro com seu email! <br> <a href=\"Login/\"/> Clique aqui </a> para entrar com email e senha ou recuperar sua senha!"; return(View()); } if (usuario.nome == null) { ModelState.AddModelError("usuario.nome", "Digite seu nome!"); } if (usuario.apelido == null) { ModelState.AddModelError("usuario.apelido", "Digite seu apelido!"); } if (usuario.email == null) { ModelState.AddModelError("usuario.email", "Digite seu email!"); } if (usuario.senha == null) { ModelState.AddModelError("usuario.senha", "Digite sua Senha!"); } else { if (usuario.senha.Equals(form.senhaConfirmacao)) { usuario.senha = funcoesUteis.Criptografar(usuario.senha); } else { ModelState.AddModelError("senhaConfirmacao", "A Senha e Confirmação da Senha não Conferem!"); return(View(ViewBag)); } } if (form.autocomplete == null) { ModelState.AddModelError("autocomplete", "Digite sua Cidade!"); } if (!ModelState.IsValid) { return(View()); } LocalidadesController loc = new LocalidadesController(); usuario.fkLocalidade = loc.carregaLocalidadeGoogle(form.administrative_area_level_2, form.country, form.administrative_area_level_1, form.longitude.ToString(), form.latitude.ToString(), form.autocomplete.ToString()); usuario.coordenadas = DbGeography.FromText(string.Format("POINT({0} {1})", form.latitude.Replace(",", "."), form.longitude.Replace(",", ".")), 4326); ImageUpload imageUpload = new ImageUpload { Width = 800 }; if (FotoPerfil != null && FotoPerfil.FileName != null) { ImageResult imageResult = imageUpload.RenameUploadFile(FotoPerfil); if (!imageResult.Success) { ModelState.AddModelError("usuario.foto", "Ocorreu um erro no Envio de Foto, Verifique o Arquivo."); return(View()); } else { usuario.foto = imageResult.ImageName; } } usuario.email = usuario.email.ToLower(); db.CAUsuario.Add(usuario); await db.SaveChangesAsync(); return(RedirectToAction("../CAUsuarios/Index")); } catch (Exception er) { ViewBag.administrative_area_level_2 = form.administrative_area_level_2; ViewBag.administrative_area_level_1 = form.administrative_area_level_1; ViewBag.country = form.country; ViewBag.autocomplete = form.autocomplete; ViewBag.longitude = form.longitude; ViewBag.latitude = form.latitude; ViewBag.Erro = er.Message.ToString(); return(View()); } return(View()); }
public async Task <ActionResult> Edit(Moto moto, HttpPostedFileBase FotoMoto) { try { CAUsuario usuario; if (Session["usuario"] == null) { return(RedirectToAction("Login", "CAUsuarios")); } else { usuario = (CAUsuario)Session["usuario"]; } Moto motovalida = await db.Moto.FindAsync(moto.pkMoto); if (motovalida.fkUsuario != usuario.pkUsuario) { return(RedirectToAction("index", "Motoes")); // alertar que nao tem acesso a esta moto. } motovalida.nomeMoto = moto.nomeMoto; motovalida.modeloMoto = moto.modeloMoto; motovalida.fkMarca = moto.fkMarca; motovalida.ativa = moto.ativa; if (ModelState.IsValid) { ImageUpload imageUpload = new ImageUpload { Width = 800 }; if (FotoMoto != null && FotoMoto.FileName != null) { ImageResult imageResult = imageUpload.RenameUploadFile(FotoMoto); if (!imageResult.Success) { ModelState.AddModelError("FotoMoto", "Ocorreu um erro no Envio de Foto, Verifique o Arquivo."); return(View()); } else { motovalida.foto = imageResult.ImageName; } } db.Entry(motovalida).State = EntityState.Modified; await db.SaveChangesAsync(); return(RedirectToAction("Index")); } } catch (Exception er) { ViewBag.Error = "Erro no Upload da Imagem"; ViewBag.fkMarca = new SelectList(db.Marca, "pkMarca", "DescricaoMarca", moto.fkMarca); return(View()); } ViewBag.fkMarca = new SelectList(db.Marca, "pkMarca", "DescricaoMarca", moto.fkMarca); return(View(moto)); }
public async Task <ActionResult> Edit(FormulariosRoles form, HttpPostedFileBase FotoCapa) { if (Session["usuario"] == null) { return(RedirectToAction("Login", "CAUsuarios")); } CAUsuario usuario = (CAUsuario)Session["usuario"]; Role role = db.Role.Find(form.role.pkRole); try { if (role.fkUsuario != usuario.pkUsuario) { return(RedirectToAction("Error_Two", "CommonViews", new { erro = "Ocorreu um erro na sua tentativa de Acesso" })); } if (form.autocomplete == null) { ModelState.AddModelError("autocomplete", "Digite a Cidade"); } if (role.titulo == null) { ModelState.AddModelError("role.titulo", "Digite eo Titulo"); } if (role.descricaoRole == null) { ModelState.AddModelError("role.descricaoRole", "Entre com a Descrição"); } if (role.totalKM == null) { ModelState.AddModelError("role.totalKM", "Digite quantos Kms devem rodar"); } if (role.localPartida == null) { ModelState.AddModelError("role.localPartida", "Qual será o ponto de encontro/partida?"); } DateTime data; if (!DateTime.TryParse(role.dataRole.ToString(), out data)) { ModelState.AddModelError("role.dataRole", "Entre com uma data valida! ex: 20/05/2017"); } if (role.dataRole == null) { ModelState.AddModelError("role.dataRole", "Digite a data! ex: 20/05/2017"); } if (role.horaRole == null) { ModelState.AddModelError("role.horaRole", "Digite a hora! ex: 07:00"); } LocalidadesController loc = new LocalidadesController(); role.fkLocalidade = loc.carregaLocalidadeGoogle(form.administrative_area_level_2, form.country, form.administrative_area_level_1, form.longitude.ToString(), form.latitude.ToString(), form.autocomplete.ToString()); ImageUpload imageUpload = new ImageUpload { Width = 800 }; if (FotoCapa != null && FotoCapa.FileName != null) { ImageResult imageResult = imageUpload.RenameUploadFile(FotoCapa); if (!imageResult.Success) { ModelState.AddModelError("FotoCapa", "Digite a hora! ex: 07:00"); return(View()); } else { role.capa = imageResult.ImageName; } } role.ativo = form.role.ativo; role.fkTipoRole = form.fkTipoRole; role.titulo = form.role.titulo; role.descricaoRole = form.role.descricaoRole; role.totalKM = form.role.totalKM; role.localPartida = form.role.localPartida; role.localDestino = form.role.localDestino; role.dataRole = form.role.dataRole; role.horaRole = form.role.horaRole; if (ModelState.IsValid) { db.Entry(role).State = EntityState.Modified; await db.SaveChangesAsync(); return(RedirectToAction("Index")); } ViewBag.fkUsuario = new SelectList(db.CAUsuario, "pkUsuario", "nome", role.fkUsuario); ViewBag.fkTipoRole = new SelectList(db.TipoRole, "pkTipoRole", "descricao", role.fkTipoRole); return(View(form)); } catch (Exception er) { ViewBag.msgErro = "Ocorreu um Erro: <br>" + er.Message.ToString(); ViewBag.fkUsuario = new SelectList(db.CAUsuario, "pkUsuario", "nome", role.fkUsuario); ViewBag.fkTipoRole = new SelectList(db.TipoRole, "pkTipoRole", "descricao", role.fkTipoRole); return(View(form)); } }