private void UploadWholeFile(HttpContextBase requestContext, List <ViewDataUploadFilesResult> statuses) { var request = requestContext.Request; for (int i = 0; i < request.Files.Count; i++) { var file = request.Files[i]; String pathOnServer = Path.Combine(StorageRoot); var fullPath = Path.Combine(pathOnServer, Path.GetFileName(file.FileName)); file.SaveAs(fullPath); //Create thumb string[] imageArray = file.FileName.Split('.'); if (imageArray.Length != 0) { String extansion = imageArray[imageArray.Length - 1].ToLower(); if (extansion != "jpg" && extansion != "png" && extansion != "jpeg") //Do not create thumb if file is not an image { } else { var ThumbfullPath = Path.Combine(pathOnServer, "thumbs"); //String fileThumb = file.FileName + ".80x80.jpg"; String fileThumb = Path.GetFileNameWithoutExtension(file.FileName) + ".jpg"; var ThumbfullPath2 = Path.Combine(ThumbfullPath, fileThumb); using (MemoryStream stream = new MemoryStream(System.IO.File.ReadAllBytes(fullPath))) { var thumbnail = new System.Web.Helpers.WebImage(stream).Resize(80, 80); thumbnail.Save(ThumbfullPath2, "jpg"); } } } statuses.Add(UploadResult(file.FileName, file.ContentLength, file.FileName)); } }
public ActionResult Edit([Bind(Include = "IDSach, IDTacGia, IDNhaXuatBan, IDTheLoai, TenSach, HinhAnh, NamXuatBan, SoLuong, SoLuongTon, TriGia, TinhTrang, MoTa")] Sach sach, HttpPostedFileBase uploadfile) { if (sach == null) { Response.StatusCode = 404; return(null); } String host = "http://qlthuvien.somee.com/Images/"; uploadfile = Request.Files[0]; //if (uploadfile.FileName != "" && uploadfile != null) //{ var fileName = System.IO.Path.GetFileName(uploadfile.FileName); var rondom = fileName; //var rondom = Guid.NewGuid() + fileName; var path = System.IO.Path.Combine(Server.MapPath("~/Images"), rondom); var filetext = System.IO.Path.GetExtension(uploadfile.FileName).Substring(1); var supportedTypes = new[] { "jpg", "jpeg", "png" }; //if (!supportedTypes.Contains(filetext)) //{ // return Content("<script language='javascript' type='text/javascript'>alert('Hello world!');</script>"); //} var image = new System.Web.Helpers.WebImage(uploadfile.InputStream); image.Save(path); // lưu vào project rondom = host + rondom; sach.HinhAnh = rondom; // luu vào database db.Entry(sach).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Sach")); }
public ActionResult ThemSach([Bind(Include = "IDSach, IDTacGia, IDNhaXuatBan, IDTheLoai, TenSach, HinhAnh, NamXuatBan, SoLuong, SoLuongTon, TriGia, TinhTrang, MoTa")] Sach sach, HttpPostedFileBase uploadfile) { if (uploadfile != null) { //return Json(sach, JsonRequestBehavior.AllowGet); String host = "http://qlthuvien.somee.com/Images/"; uploadfile = Request.Files[0]; //if (uploadfile.FileName != "" && uploadfile != null) //{ var fileName = System.IO.Path.GetFileName(uploadfile.FileName); var rondom = fileName; //var rondom = Guid.NewGuid() + fileName; var path = System.IO.Path.Combine(Server.MapPath("~/Images"), rondom); var filetext = System.IO.Path.GetExtension(uploadfile.FileName).Substring(1); var supportedTypes = new[] { "jpg", "jpeg", "png" }; var image = new System.Web.Helpers.WebImage(uploadfile.InputStream); image.Save(path); // lưu vào project rondom = host + rondom; sach.HinhAnh = rondom; // luu vào database } sach.IDSach = ""; sach.SoLuong = 0; sach.SoLuongTon = 0; sach.TinhTrang = 1; db.Saches.Add(sach); db.SaveChanges(); return(RedirectToAction("Sach")); }
public ActionResult Upload(string role) { string userName = OtherFunctions.StripDomain(User.Identity.Name); int userId = userService.GetUserId(userName); // Пользователю запрещен просмотр if (!userService.AllowView(userId)) { return RedirectToAction("ShowError", "Actions", new { resultType = Constants.ResultTypes.UnAuthorized.ToString() }); } var imageData = new System.Web.Helpers.WebImage(Request.InputStream); MemoryStream stream = new MemoryStream(imageData.GetBytes()); Image image = Image.FromStream(stream); string dirName = "/content/tempImages/" + userName; try { if (!Directory.Exists(dirName)) { Directory.CreateDirectory(dirName); } image.Save(dirName + "/" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg"); } catch(Exception exc) { } string qrText = DecodeImage(image); // Не распознано if (qrText == null) { return RedirectToAction("ShowError", "Actions", new{resultType = Constants.ResultTypes.DecodeError.ToString()}); } QrDoc qrDoc = new QrDoc(qrText); // ошибка парсинга if (!qrDoc.IsInited) { return RedirectToAction("ShowError", "Actions", new { resultType = Constants.ResultTypes.ParseError.ToString() }); } else { int ationId; if (int.TryParse(role, out ationId)) { qrDoc.ActionId = ationId; } TempData["qrDoc"] = qrDoc; return RedirectToAction("Index", "Actions"); } }
/// <summary> /// Save photo to disk, used by Edit and Register with two different models. model.Photo, this, string model.CategoryName, string model.SubCategoryName /// </summary> /// <param name="photo">HttpPostedFileWrapper</param> /// <param name="controller">Controller calling</param> /// <returns>Path where photo is stored with it's calculated filename, or default photo "BlankPhoto.jpg" or null on error</returns> public static string[] SaveAcdfPhotoFileToDisk(System.Web.Helpers.WebImage webImage, System.Web.Mvc.Controller controller, string categoryName, string subCategoryName) { string[] paths = new string[2]; string photoPath = string.Empty; string thumbPath = string.Empty; string fileName = string.Empty; string thumbFileName = string.Empty; string subCatName = subCategoryName.Contains("AUCUNE") ? string.Empty : subCategoryName; if (webImage != null) { // If photo is uploaded calculate his name string guid = Guid.NewGuid().ToString(); fileName = guid + "_" + webImage.FileName; thumbFileName = guid + "_thumb_" + webImage.FileName; //Calculate photoUrl and save photo on disk try { string path = HttpContext.Current.Request.ApplicationPath + "/Medias/_Photos/" + categoryName + @"\" + subCatName; //string path = @"~/Medias\_Photos\" + categoryName + @"\" + subCatName; //string path = @"/ACDF/Medias\_Photos\"; string filePath = Path.Combine(controller.Server.MapPath(path), fileName); webImage.AddTextWatermark("http://jow-alva.net/ACDF", "White", 15); webImage.Save(filePath); photoPath = Path.Combine(HttpRuntime.AppDomainAppVirtualPath, path, fileName); string thumbFilePath = Path.Combine(controller.Server.MapPath(path), thumbFileName); webImage.Resize(150, 150, preserveAspectRatio: true).Save(thumbFilePath); thumbPath = Path.Combine(HttpRuntime.AppDomainAppVirtualPath, path, thumbFileName); paths[0] = photoPath; paths[1] = thumbPath; } catch (Exception ex) { // Handled exception catch code Helpers.Utils.SignalExceptionToElmahAndTrace(ex, controller); throw ex; //return null; } } else { // Handled exception catch code //TODO: Helpers.Utils.SignalExceptionToElmahAndTrace(null, controller); return(null); } return(paths); }
public JsonResult UploadIconLoaiHoSo() { try { var userId = _session.UserId; //Check input if (Request.Files.Count <= 0 || Request.Files[0] == null) { throw new UserFriendlyException(L("ProfilePicture_Change_Error")); } var file = Request.Files[0]; if (file.ContentLength > 1048576) //1MB. { throw new UserFriendlyException(L("ProfilePicture_Warn_SizeLimit")); } //Check file type & format var fileImage = System.Drawing.Image.FromStream(file.InputStream); var acceptedFormats = new List <ImageFormat> { ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.Gif }; if (!acceptedFormats.Contains(fileImage.RawFormat)) { throw new ApplicationException("Uploaded file is not an accepted image file !"); } var webImage = new System.Web.Helpers.WebImage(Request.Files[0].InputStream); byte[] imgByteArray = webImage.GetBytes(); fileImage.Dispose(); return(Json(new AjaxResponse(new { data = imgByteArray }))); } catch (UserFriendlyException ex) { Logger.Error($"{DateTime.Now.ToString("HH:mm:ss dd/MM/yyyy")} UploadIconLoaiHoSo {ex.Message} {JsonConvert.SerializeObject(ex)}"); return(Json(new AjaxResponse(new ErrorInfo(ex.Message)))); } }
public ActionResult AddGown(int password, int id_catgory, int id_season, string is_long, int price, string is_light, int color, int num_of_dress, string fileset, string arrFiles, string arrSizes) { System.Web.Helpers.WebImage photo = null; //var imagePath = ""; //int error = 0; //var q = db.Renters.FirstOrDefault(p => p.password == password); //if (ModelState.IsValid && q != null) //{ // string[] arrayFiles; // string[] arraySizes; // string[] arrfilenames; // arraySizes = arrSizes.Split(' ').ToArray(); // arrayFiles = arrFiles.Split('?').ToArray(); // int idGown = 0; // foreach (Gowns currentGown in db.Gowns) // { // idGown = currentGown.id_gown; // } // if (arraySizes.Count() > 2) // { // Sets set = new Sets(); // int id = 0; // foreach (Sets currentset in db.Sets) // { // id = currentset.id_set; // } // set.num_of_set = arraySizes.Count() - 1; // set.id_set = id + 1; // arrfilenames = arrayFiles[0].Split('\\').ToArray(); // var filenameSet = Guid.NewGuid().ToString() + "_" + arrfilenames[arrfilenames.Count() - 1]; // set.picture = filenameSet; // photo = WebImage.GetImageFromRequest("fileset"); // if (photo != null) // { // //Path.GetFileName(photo.FileName); // imagePath = @"Images\" + filenameSet; // photo.Save(@"~\" + imagePath); // } // int i = 0; // foreach (string size in arraySizes) // { // if (size != "") // { // Gowns gown = new Gowns(); // arrfilenames = arrayFiles[i].Split('\\').ToArray(); // gown.id_gown = idGown + 1; // gown.id_renter = q.id_renter; // gown.id_catgory = id_catgory; // var filename = Guid.NewGuid().ToString() + "_" + arrfilenames[arrfilenames.Count() - 1]; // gown.picture = filename.ToString(); // gown.id_season = id_season; // if (is_long == "ארוך") // gown.is_long = true; // else gown.is_long = false; // gown.price = price; // if (is_light == "בהיר") // gown.is_light = true; // else gown.is_light = false; // gown.color = color; // gown.id_set = set.id_set; // gown.size = int.Parse(size); // photo = WebImage.GetImageFromRequest("file" + ++i); // if (photo != null) // { // //photo.Resize((int)(photo.Width*0.8), (int)(photo.Height * 0.8)); // //Path.GetFileName(photo.FileName); // imagePath = @"Images\" + filename; // photo.Save(@"~\" + imagePath); // } // db.Sets.Add(set); // db.Gowns.Add(gown); // } // } // } // else // { // Gowns gown = new Gowns(); // gown.id_gown = idGown + 1; // gown.id_renter = q.id_renter; // gown.id_catgory = id_catgory; // arrfilenames = arrayFiles[0].Split('\\').ToArray(); // var filename = Guid.NewGuid().ToString() + "_" + arrfilenames[arrfilenames.Count() - 1]; // gown.picture = filename.ToString(); // gown.id_season = id_season; // if (is_long == "ארוך") // gown.is_long = true; // else gown.is_long = false; // gown.price = price; // if (is_light == "בהיר") // gown.is_light = true; // else gown.is_light = false; // gown.color = color; // gown.id_set = 1; // gown.size = int.Parse(arraySizes[0]); // photo = WebImage.GetImageFromRequest("file1"); // if (photo != null) // { // //Path.GetFileName(photo.FileName); // imagePath = @"Images\" + filename; // photo.Save(@"~\" + imagePath); // } // db.Gowns.Add(gown); // } // db.SaveChanges(); // // return RedirectToAction("Index"); // return RedirectToAction("Index", "Home"); //} //else //{ // if (q == null) // { // error = 1; // } //} //ViewBag.id_catgory = new SelectList(db.Catgories, "id_catgory", "catgory"); //ViewBag.id_renter = new SelectList(db.Renters, "id_renter", "fname"); //ViewBag.id_season = new SelectList(db.Seasons, "id_season", "season"); //ViewBag.id_season = new SelectList(db.Seasons, "id_season", "season"); //ViewBag.id_set = new SelectList(db.Sets, "id_set", "id_set"); //ViewBag.color = new SelectList(db.Colors, "id_color", "color"); return(RedirectToAction("AddGown")); }
public async Task <ActionResult> Create(IssueVM model) { if (!ModelState.IsValid) { ModelState.AddModelError("", "Hata Oluştu."); return(RedirectToAction("Create", "Issue", model)); } try { var id = HttpContext.GetOwinContext().Authentication.User.Identity.GetUserId(); var user = NewUserManager().FindById(id); var issue = new Issue() { Description = model.Description, IssueState = model.IssueState, Location = model.Location == Models.Enums.Locations.KonumYok ? user.Location : model.Location, ProductType = model.ProductType, CustomerId = model.CustomerId, PurchasedDate = model.PurchasedDate, PhotoPath = model.PhotoPath, ServiceCharge = model.ServiceCharge, ClosedDate = model.ClosedDate, CreatedDate = model.CreatedDate, OperatorId = model.OperatorId, TechReport = model.TechReport }; switch (issue.ProductType) { case Models.Enums.ProductTypes.Buzdolabı: if (issue.PurchasedDate.AddYears(1) > DateTime.Now) { issue.WarrantyState = true; } break; case Models.Enums.ProductTypes.BulaşıkMakinesi: if (issue.PurchasedDate.AddYears(2) > DateTime.Now) { issue.WarrantyState = true; } break; case Models.Enums.ProductTypes.Fırın: if (issue.PurchasedDate.AddYears(3) > DateTime.Now) { issue.WarrantyState = true; } break; case Models.Enums.ProductTypes.ÇamaşırMakinesi: if (issue.PurchasedDate.AddYears(4) > DateTime.Now) { issue.WarrantyState = true; } break; case Models.Enums.ProductTypes.Mikrodalga: if (issue.PurchasedDate.AddYears(5) > DateTime.Now) { issue.WarrantyState = true; } break; default: if (issue.PurchasedDate.AddYears(2) > DateTime.Now) { issue.WarrantyState = true; } break; } if (issue.WarrantyState) { issue.ServiceCharge = 0; } var repo = new IssueRepo(); repo.Insert(issue); var fotorepo = new PhotographRepo(); if (model.PostedPhoto.Count > 0) { model.PostedPhoto.ForEach(file => { if (file == null || file.ContentLength <= 0) { var filepath2 = Server.MapPath("~/assets/images/image-not-available.png"); var img2 = new WebImage(filepath2); img2.Resize(250, 250, false); img2.Save(filepath2); fotorepo.Insert(new Photograph() { IssueId = issue.Id, Path = "/assets/images/image-not-available.png" }); return; } var fileName = Path.GetFileNameWithoutExtension(file.FileName); var extName = Path.GetExtension(file.FileName); fileName = StringHelpers.UrlFormatConverter(fileName); fileName += StringHelpers.GetCode(); var directorypath = Server.MapPath("~/Upload/"); var filepath = Server.MapPath("~/Upload/") + fileName + extName; if (!Directory.Exists(directorypath)) { Directory.CreateDirectory(directorypath); } file.SaveAs(filepath); var img = new WebImage(filepath); img.Resize(250, 250, false); img.Save(filepath); fotorepo.Insert(new Photograph() { IssueId = issue.Id, Path = "/Upload/" + fileName + extName }); }); } var fotograflar = fotorepo.GetAll(x => x.IssueId == issue.Id).ToList(); var foto = fotograflar.Select(x => x.Path).ToList(); issue.PhotoPath = foto; repo.Update(issue); TempData["Message"] = "Arıza kaydınız başarı ile oluşturuldu."; var emailService = new EmailService(); var body = $"Merhaba <b>{user.Name} {user.Surname}</b><br>Arıza kaydınız başarıyla oluşturuldu.Birimlerimiz sorunu çözmek için en kısa zamanda olay yerine intikal edecektir.<br><br> Ayrıntılı bilgi için telefon numaramız:<i>0212 684 75 33</i>"; await emailService.SendAsync(new IdentityMessage() { Body = body, Subject = "Arıza kaydı oluşturuldu." }, user.Email); var issueLog = new IssueLog() { IssueId = issue.Id, Description = "Arıza Kaydı Oluşturuldu.", FromWhom = "Müşteri" }; new IssueLogRepo().Insert(issueLog); return(RedirectToAction("Index", "Issue")); } catch (DbEntityValidationException ex) { TempData["Message3"] = new ErrorVM() { Text = $"Bir hata oluştu: {EntityHelpers.ValidationMessage(ex)}", ActionName = "Create", ControllerName = "Issue", ErrorCode = 500 }; return(RedirectToAction("Error500", "Home")); } catch (Exception ex) { TempData["Message2"] = new ErrorVM() { Text = $"Bir hata oluştu {ex.Message}", ActionName = "Create", ControllerName = "Issue", ErrorCode = 500 }; return(RedirectToAction("Error500", "Home")); } }