public void addImage(ApplicationDbContext DB, HttpPostedFileWrapper image) { if(DB.galleryImages.Where(g => g.id == id).Any()) { GalleryImage gi = DB.galleryImages.Where(g => g.id == id).FirstOrDefault(); if (image != null && image.ContentLength > 0) { string path = "/content/images/uploads/galleries/" + gi.galleryID; bool exists = Directory.Exists(HttpContext.Current.Server.MapPath(path)); if (!exists) { Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path)); } path = path + "/" + gi.id + Path.GetExtension(image.FileName); image.SaveAs(HttpContext.Current.Server.MapPath(path)); gi.image = path; } DB.SaveChanges(); } }
public void Insert(FormCollection fc, HttpPostedFileWrapper file) { if (file != null && fc["NameAds"].ToString() != "") { Ads _pro = new Ads(); var allowedExtensions = new[] { ".JPG", ".PNG", ".JPEG", ".GIF" }; var fileName = Path.GetFileName(file.FileName); //getting only file name(ex-ganesh.jpg) var ext = (Path.GetExtension(file.FileName)).ToUpper(); //getting the extension(ex-.jpg) if (allowedExtensions.Contains(ext)) //check what type of extension { string name = Path.GetFileNameWithoutExtension(fileName); //getting file name without extension string myfile = UnitilHelper.convertToUnSign(name) + DateTime.Now.Millisecond + ext; //appending the name with id string path = System.IO.Path.Combine(Server.MapPath("/Upload"), myfile); string urlads = "Upload/" + myfile; try { file.SaveAs(path); _pro.Image = urlads; _pro.IsDelete = false; _pro.IsShow = fc["optionsRadios"] == "SetHot" ? true : false; _pro.Name = fc["NameAds"]; _pro.URL = fc["Url"]; _adsService.InsertAds(_pro); _unitOfWork.SaveChanges(); } catch { } } } Response.Redirect("Index"); }
public void udate(ApplicationDbContext DB, string title, string text, HttpPostedFileWrapper image, string tag) { this.tag = tag; addImage(DB, image); addContent(DB, "title", title); addContent(DB, "text", text); }
private HttpResponseMessage ProcessFile() { int userId = 1; var files = HttpContext.Current.Request.Files; string fileTypeIdStr = HttpContext.Current.Request.Form.Get("fileType"); int fileTypeId = 1; try { fileTypeId = Int32.Parse(fileTypeIdStr); } catch { } var statuses = new List<ViewDataUploadFileResult>(); FilesBL bl = new FilesBL(); for (var i = 0; i < files.Count; i++) { var st = bl.SaveFile(x => { var file = new HttpPostedFileWrapper(files[i]); x.FileContentLength = file.ContentLength; x.FileData = new byte[x.FileContentLength]; file.InputStream.Read(x.FileData, 0, x.FileContentLength); x.FileTypeId = fileTypeId; x.DeleteUrl = "/api/Files"; x.StorageDirectory = "/Files/"; x.UrlPrefix = "/Files/Download"; //overriding defaults x.FileName = files[i].FileName; x.ThrowExceptions = true; }, userId); statuses.Add(st); } var response = Request.CreateResponse(HttpStatusCode.OK, new { files = statuses }); //for IE9 which does not accept application/json if (HttpContext.Current.Request.Headers["Accept"] != null && !HttpContext.Current.Request.Headers["Accept"].Contains("application/json")) { if (response.Content == null) { response.Content = new StringContent(""); // The media type for the StringContent created defaults to text/plain. } response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain"); } return response; }
public void UploadNow(HttpPostedFileWrapper upload) { if (upload != null) { var imageName = upload.FileName; var path = Path.Combine(Server.MapPath("~/Upload/Images"), imageName);//TODO перенести путь в config upload.SaveAs(path); } }
public void UploadNow(HttpPostedFileWrapper upload) { if (upload != null) { var imageName = upload.FileName; var path = System.IO.Path.Combine(Server.MapPath("~/Upload/Images"), imageName); upload.SaveAs(path); } }
public int Add(HttpPostedFileWrapper file) { var tempImage = new byte[file.ContentLength]; file.InputStream.Read(tempImage, 0, file.ContentLength); var entity = new File { ContentType = file.ContentType, BinaryData = tempImage, FileName = file.FileName }; var added = _fileContext.Insert(entity); return added.Id; }
public bool addImage(int galleryID, string title, string text, HttpPostedFileWrapper image, string tag) { try { using (ApplicationDbContext DB = new ApplicationDbContext()) { ImageGallery gal = DB.gallerys.Where(g => g.id == id).FirstOrDefault(); GalleryImage gi = new GalleryImage(); gi.galleryID = galleryID; gi.tag = tag; gal.galleryImages.Add(gi); DB.SaveChanges(); if (image != null && image.ContentLength > 0) { string path = "/content/images/uploads/galleries/" + galleryID; bool exists = Directory.Exists(HttpContext.Current.Server.MapPath(path)); if (!exists) { Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path)); } path = path + "/" + gi.id + Path.GetExtension(image.FileName); image.SaveAs(HttpContext.Current.Server.MapPath(path)); gi.image = path; } DB.SaveChanges(); gi.addText(DB, text); gi.addTitle(DB, title); } return true; } catch(Exception) { return false; } }
public RedirectToRouteResult NewPicture(int NodeID, System.Web.HttpPostedFileWrapper picturefile, string picturetitle = "") { Node currNode = repository.Nodes .FirstOrDefault(n => n.NodeID == NodeID); repository.NewPicture(currNode.NodeID, picturefile.FileName.Substring(picturefile.FileName.IndexOf("images")), picturetitle); TempData["message"] = string.Format("Picture: {0} for Node: {1}, {2} ... has been created", picturetitle, currNode.NodeID, currNode.Heading); ViewBag.SelectedNodeHeading = currNode.Heading; return(RedirectToAction("Index", "Book", new { NodeID = currNode.NodeID })); }
public JsonResult Add(System.Web.HttpPostedFileWrapper postedfile, bool RequireImage, njAsyncFile njAsyncFile) { try { var result = njAsyncFile.AddItem(postedfile, RequireImage); return(Json(new { Result = "OK", Records = new List <njAsyncFileUploadResult> { result }, })); } catch { return(Json(new { Result = "ERROR", Message = "ثبت فایل انجام نشد" })); } }
public string GetFileName(Property property, HttpPostedFileWrapper file) { switch (property.FileOptions.NameCreation) { default: case NameCreation.OriginalFileName: return file.FileName; case NameCreation.Guid: return "{0}.jpg".Fill(Guid.NewGuid()); case NameCreation.Timestamp: return "{0}.jpg".Fill(DateTime.Now.ToString("ddMMyyhhmmss")); case NameCreation.UserInput: return "test.jpg"; } }
public string MultiUpload(System.Web.HttpPostedFileWrapper FileBytes, string ConType, string NameFile, int pos) { int len = FileBytes.ContentLength; var buf = new byte[len]; FileBytes.InputStream.Read(buf, 0, len); string newpath = addFile1(NameFile, ConType); using (FileStream fs = System.IO.File.Open(newpath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write)) { fs.Position = pos; fs.Write(buf, 0, len); } return("test"); }
public ActionResult AddProduct(product_productType_ViewModel model, System.Web.HttpPostedFileWrapper image) { if (ModelState.IsValid) { db.products.Add(new product { name = model.product_name, unit_price = model.unit_price, promotion_price = model.promotion_price , image = image.FileName, @new = model.@new, unit = model.unit, description = model.description, id_product_type = model.id_product_type, created_at = System.DateTime.Now, updated_at = System.DateTime.Now }); image.SaveAs(Server.MapPath(Path.Combine("~/image/product/", image.FileName))); db.SaveChanges(); return(RedirectToAction(actionName: "Index", controllerName: "AdminProduct")); } return(View(model)); }
public ActionResult Create([Bind(Include = "Id,Name,Description,Price,Date")] Dish dish, HttpPostedFileWrapper photo) { if (ModelState.IsValid) { if(photo != null) { using (var ms = new System.IO.MemoryStream()) { photo.InputStream.CopyTo(ms); dish.Photo = ms.ToArray(); } } db.Dish.Add(dish); db.SaveChanges(); return RedirectToAction("Index"); } return View(dish); }
public ActionResult Edit(product_productType_ViewModel model, System.Web.HttpPostedFileWrapper image) { var obj = db.products.FirstOrDefault(x => x.id_product == model.id_product); obj.name = model.product_name; obj.unit_price = model.unit_price; obj.promotion_price = model.promotion_price; if (image != null) { obj.image = image.FileName; image.SaveAs(Server.MapPath(Path.Combine("~/image/product/", image.FileName))); } obj.id_product_type = model.id_product_type; obj.@new = model.@new; obj.unit = model.unit; obj.updated_at = System.DateTime.Now; db.Entry(obj).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index", "AdminProduct")); }
private UploadFileResult SaveUploadFolder(HttpPostedFile httpPostedFile) { UploadFileResult uploadResult = null; var user = HttpContext.Current.User; HttpPostedFileBase photo = new HttpPostedFileWrapper(httpPostedFile); var loggedOnReadOnlyUserId = user.Identity.GetUserId(); if (HttpContext.Current.Request.Files.AllKeys.Any()) { var uploadFolderPath = HostingEnvironment.MapPath(string.Concat(SiteConstants.UploadFolderPath, loggedOnReadOnlyUserId)); if (string.IsNullOrEmpty(uploadFolderPath) == false && Directory.Exists(uploadFolderPath) == false) { Directory.CreateDirectory(uploadFolderPath); } uploadResult = AppHelpers.UploadFile(photo, uploadFolderPath); } return uploadResult; }
public ActionResult Upload(HttpPostedFileWrapper qqfile) { var extension = Path.GetExtension(qqfile.FileName); if (!string.IsNullOrWhiteSpace(extension)) { var mimeType = Config.MimeTypes.FirstOrDefault(p => string.Compare(p.Extension, extension, 0) == 0); //если изображение if (mimeType != null && PreviewCreator.SupportMimeType(mimeType.Name)) { //тут сохраняем в файл var filePath = Path.Combine("/Content/files", qqfile.FileName); qqfile.SaveAs(Server.MapPath(filePath)); var filePreviewPath = Path.Combine("/Content/files/previews", qqfile.FileName); var previewIconSize = Config.IconSizes.FirstOrDefault(c => c.Name == "AvatarSize"); if (previewIconSize != null) { PreviewCreator.CreateAndSavePreview(qqfile.InputStream, new Size(previewIconSize.Width, previewIconSize.Height), Server.MapPath(filePreviewPath)); } return Json(new { success = true, result = "error", data = new { filePath, filePreviewPath } }); } } return Json(new { error = "Нужно загрузить изображение", success = false }); }
public JsonResult Create(HttpPostedFileWrapper imageFile) { JsonResult json = new JsonResult(); if (imageFile == null || imageFile.ContentLength == 0) { json.Data = new { status = "no_file" }; return json; } var fileName = String.Format("{0}", Guid.NewGuid().ToString()); var imagePath = Path.Combine(Server.MapPath(Url.Content("~/Content/UserImages")), fileName); imageFile.SaveAs(imagePath + ".jpg"); // resize var oryginalImage = Image.FromFile(imagePath + ".jpg"); var Image800 = ResizeImage(oryginalImage, 600, 800); var image200 = ResizeImage(oryginalImage, 200, 200); var image450width = ResizeImage(oryginalImage, 450, -1); // save to Image800.Save(imagePath + "_800.jpg"); image200.Save(imagePath + "_200.jpg"); image450width.Save(imagePath + "_450width.jpg"); // save to db var photo = new Photo(); photo.prefix = fileName; photo.MembershipUserID = (Guid)Membership.GetUser().ProviderUserKey; db.Photos.Add(photo); db.SaveChanges(); json.Data = new { status = "ok", redirect = Url.Action("Details", "Photo", new { id = photo.PhotoID.ToString() }) }; return json; }
public ActionResult EditSuggestion(GATE_ComponentRequest suggestion, HttpPostedFileWrapper pictureUpload = null) { if (!suggestion.InStock) { if (suggestion.CurrentSuggestion.Price == null) { ModelState.AddModelError("MaterialSuggestion.Price", "Price is required"); } if (suggestion.CurrentSuggestion.Label == null) { ModelState.AddModelError("MaterialSuggestion.Label", "Label is required"); } } else { suggestion.CurrentSuggestion.Label = "In Stock"; suggestion.CurrentSuggestion.Price = 0; } if (pictureUpload != null && pictureUpload.ContentType.Substring(0, 5) != "image") { ModelState.AddModelError("pictureUpload", "The file you tried to insert is not an image file, you should use .jpg, .png or .gif"); } var componentRequest = DB.GATE_ComponentRequest.Include(x => x.CurrentSuggestion) .Include(x => x.PreviousSuggestion) .Where(x => x.ComponentId == suggestion.ComponentId) .Select(x => x).FirstOrDefault(); if (componentRequest.PreviousMaterialSuggestedId == null) { var matSuggestion = new GATE_MaterialSuggestion { Label = componentRequest.CurrentSuggestion.Label, Price = componentRequest.CurrentSuggestion.Price, DeliveryDate = componentRequest.CurrentSuggestion.DeliveryDate, CurrencyId = componentRequest.CurrentSuggestion.CurrencyId, IsNotStandardProduct = componentRequest.CurrentSuggestion.IsNotStandardProduct, PictureId = componentRequest.CurrentSuggestion.PictureId, InStock = componentRequest.CurrentSuggestion.InStock }; componentRequest.PreviousSuggestion = matSuggestion; DB.GATE_MaterialSuggestion.Add(componentRequest.PreviousSuggestion); DB.SaveChanges(); } else { componentRequest.PreviousSuggestion.Label = componentRequest.CurrentSuggestion.Label; componentRequest.PreviousSuggestion.Price = componentRequest.CurrentSuggestion.Price; componentRequest.PreviousSuggestion.DeliveryDate = componentRequest.CurrentSuggestion.DeliveryDate; componentRequest.PreviousSuggestion.CurrencyId = componentRequest.CurrentSuggestion.CurrencyId; componentRequest.PreviousSuggestion.IsNotStandardProduct = componentRequest.CurrentSuggestion.IsNotStandardProduct; componentRequest.PreviousSuggestion.PictureId = componentRequest.CurrentSuggestion.PictureId; componentRequest.PreviousSuggestion.InStock = componentRequest.CurrentSuggestion.InStock; DB.Entry(componentRequest.PreviousSuggestion).State = EntityState.Modified; DB.SaveChanges(); } componentRequest.CurrentSuggestion.Label = suggestion.CurrentSuggestion.Label; componentRequest.CurrentSuggestion.Price = suggestion.CurrentSuggestion.Price; componentRequest.CurrentSuggestion.DeliveryDate = suggestion.CurrentSuggestion.DeliveryDate; componentRequest.CurrentSuggestion.CurrencyId = suggestion.CurrentSuggestion.CurrencyId; componentRequest.CurrentSuggestion.IsNotStandardProduct = suggestion.CurrentSuggestion.IsNotStandardProduct; componentRequest.CurrentSuggestion.InStock = suggestion.InStock; if (pictureUpload != null && pictureUpload.ContentType.Substring(0, 5) == "image") { var b = new BinaryReader(pictureUpload.InputStream); byte[] binData = b.ReadBytes(pictureUpload.ContentLength); var pictureFile = new GATE_SuggestionPicture { PictureData = binData }; componentRequest.CurrentSuggestion.GATE_SuggestionPicture = pictureFile; } DB.Entry(componentRequest.CurrentSuggestion).State = EntityState.Modified; DB.SaveChanges(); return new RedirectResult(Url.Action("Pending") + "#tr" + componentRequest.MaterialRequestId); }
public ActionResult CreateSuggestion(GATE_ComponentRequest suggestion, HttpPostedFileWrapper pictureUpload) { //TODO reimplement with the new Stock and password tables #stock if (!suggestion.InStock) { if (suggestion.CurrentSuggestion.Price == null) { ModelState.AddModelError("MaterialSuggestion.Price", "Price is required"); } if (suggestion.CurrentSuggestion.Label == null) { ModelState.AddModelError("MaterialSuggestion.Label", "Label is required"); } } else { suggestion.CurrentSuggestion.Label = "In Stock"; suggestion.CurrentSuggestion.Price = 0; } if (pictureUpload != null && pictureUpload.ContentType.Substring(0, 5) != "image") { ModelState.AddModelError("pictureUpload", "The file you tried to insert is not an image file, you should use .jpg, .png or .gif"); } var componentRequest = DB.GATE_ComponentRequest.Find(suggestion.ComponentId); GATE_MaterialSuggestion matSuggestion = suggestion.CurrentSuggestion; componentRequest.CurrentSuggestion = matSuggestion; if (pictureUpload != null && pictureUpload.ContentType.Substring(0, 5) == "image") { var b = new BinaryReader(pictureUpload.InputStream); byte[] binData = b.ReadBytes(pictureUpload.ContentLength); var pictureFile = new GATE_SuggestionPicture { PictureData = binData, }; componentRequest.CurrentSuggestion.GATE_SuggestionPicture = pictureFile; } else { componentRequest.CurrentSuggestion.PictureId = null; } DB.GATE_MaterialSuggestion.Add(matSuggestion); DB.SaveChanges(); return new RedirectResult(Url.Action("Pending") + "#tr" + componentRequest.MaterialRequestId); }
public WrappedJsonResult EditEventPhoto(HttpPostedFileWrapper imageFile, int Event_Id) { if (imageFile == null || imageFile.ContentLength == 0) { return new WrappedJsonResult { Data = new { IsValid = false, Message = "No file was uploaded.", ImagePath = string.Empty } }; } string mimeType = imageFile.ContentType; Stream fileStream = imageFile.InputStream; string fileName = Path.GetFileName(imageFile.FileName); int fileLength = imageFile.ContentLength; byte[] fileData = new byte[fileLength]; fileStream.Read(fileData, 0, fileLength); Event Xevent = db.Events.FirstOrDefault(e => e.Event_Id == Event_Id); Xevent.Event_Photo = fileData; Xevent.Event_PhotoMimeType = mimeType; Xevent.Event_PhotoFileName = fileName; //db.Events.Attach(Xevent); db.Entry(Xevent).State = EntityState.Modified; db.SaveChanges(); var fileNameZ = String.Format("{0}.jpg", Guid.NewGuid().ToString()); var imagePath = Path.Combine(Server.MapPath(Url.Content("~/Uploads")), fileNameZ); imageFile.SaveAs(imagePath); return new WrappedJsonResult { Data = new { IsValid = true, Message = string.Empty, ImagePath = Url.Content(String.Format("~/Uploads/{0}", fileNameZ)) } }; }
public WrappedJsonResult UploadSingleFile(HttpPostedFileWrapper uploadFile, string SelectedFolderId, string RootFolderType) { var rootFolderType = (MediaType)Enum.Parse(typeof(MediaType), RootFolderType); if (uploadFile != null && FileFormatIsValid(rootFolderType, uploadFile.ContentType)) { UploadFileRequest request = new UploadFileRequest { RootFolderId = SelectedFolderId.ToGuidOrDefault(), Type = rootFolderType, FileLength = uploadFile.ContentLength, FileName = uploadFile.FileName, FileStream = uploadFile.InputStream }; var media = GetCommand<UploadCommand>().ExecuteCommand(request); if (media != null) { return new WrappedJsonResult { Data = new { Success = true, Id = media.Id, fileName = media.OriginalFileName, fileSize = media.Size, Version = media.Version, Type = request.Type, IsProcessing = !media.IsUploaded.HasValue, IsFailed = media.IsUploaded == false, } }; } } List<string> messages = new List<string>(); messages.AddRange(Messages.Error); return new WrappedJsonResult { Data = new { Success = false, Messages = messages.ToArray() } }; }
public FileUploadHttpPostedFileWrapper(HttpPostedFileWrapper file):this() { this.postedFile = file; }
public ActionResult editSchoolStation(int stationID, int schoolID, SchoolStation station, string callback, HttpPostedFileWrapper image) { ajaxReturnData data = new ajaxReturnData(); try { using (ApplicationDbContext DB = new ApplicationDbContext()) { station.id = stationID; DB.Stations.Attach(station); DB.Entry(station).State = EntityState.Unchanged; DB.Entry(station).Property(s => s.line).IsModified = true; DB.Entry(station).Property(s => s.name).IsModified = true; DB.Entry(station).Property(s => s.distance).IsModified = true; if (image != null && image.ContentLength > 0) { string path = "/content/images/uploads/schools/" + schoolID; bool exists = Directory.Exists(Server.MapPath(path)); if (!exists) { Directory.CreateDirectory(Server.MapPath(path)); } path = path + "/station" + station.id + Path.GetExtension(image.FileName); image.SaveAs(Server.MapPath(path)); station.image = path; DB.Entry(station).Property(s => s.image).IsModified = true; } DB.SaveChanges(); } if (string.IsNullOrEmpty(callback)) { data.statusCode = (int)statusCodes.success; } else { data.statusCode = (int)statusCodes.successRun; data.callback = callback; } data.message = "station updated"; return Json(data); } catch (Exception ex) { data.statusCode = (int)statusCodes.fail; data.message = "Failed to update station; " + ex.Message; return Json(data); } }
public JsonResult UploadPreImage(HttpPostedFileWrapper qqfile) { _photoEditor = new PhotoEditor(UrlToLocal(TempFolder), UrlToLocal(JewelPHotoFolder)); try { var fName=_photoEditor.SaveTempFile(qqfile); return Json(new { success = true, errorMessage = string.Empty, fileName = "/Content/images/Temp" + "/" + fName }); } catch (Exception e) { return Json(new {success = true, errorMessage = e.Message}); } }
public void UploadNow(HttpPostedFileWrapper upload) { if (upload != null) { byte[] fileData = null; var postedFileBase = Request.Files[0]; if (postedFileBase != null) { using (var binaryReader = new BinaryReader(postedFileBase.InputStream)) { var httpPostedFileBase = postedFileBase; fileData = binaryReader.ReadBytes(httpPostedFileBase.ContentLength); } } new EmailMarketingService().EnviaArquivo(upload.FileName, fileData); } }
private static bool IsImage(HttpPostedFileWrapper file) { return Regex.IsMatch(file.ContentType, "image/\\S+"); }
public ActionResult editLocation(int locationID, int schoolID, string description, Location location, string callback, HttpPostedFileWrapper image) { ajaxReturnData data = new ajaxReturnData(); try { using (ApplicationDbContext DB = new ApplicationDbContext()) { location.id = locationID; DB.Locations.Attach(location); DB.Entry(location).State = EntityState.Unchanged; DB.Entry(location).Property(l => l.name).IsModified = true; //DB.Entry(location).Property(l => l.city).IsModified = true; location.addContent(DB, "description", description); if (image != null && image.ContentLength > 0) { string path = "/content/images/uploads/locations/" + locationID; //bool existsfirst = System.IO.Directory.Exists(Server.MapPath(path)); bool exists = System.IO.Directory.Exists(Server.MapPath(path)); if (!exists) { Directory.CreateDirectory(Server.MapPath(path)); } path = path + "/locationImage" + Path.GetExtension(image.FileName); image.SaveAs(Server.MapPath(path)); location.image = path; DB.Entry(location).Property(l => l.image).IsModified = true; } DB.SaveChanges(); School school = new School(); school.id = schoolID; //school.schoolLocation = location; school.locationID = location.id; school.features = new SchoolFeatures(); DB.Schools.Attach(school); DB.Entry(school).State = EntityState.Unchanged; DB.Entry(school).Property(s => s.locationID).IsModified = true; DB.SaveChanges(); } if (string.IsNullOrEmpty(callback)) { data.statusCode = (int)statusCodes.success; } else { data.statusCode = (int)statusCodes.successRun; data.callback = callback; } data.message = "location updated"; return Json(data); } catch (Exception ex) { data.statusCode = (int)statusCodes.fail; data.message = "Failed to update location; " + ex.Message; return Json(data); } }
/// <summary> /// Sets and uploads the file from a HttpPostedFileWrapper object as the property value /// </summary> /// <param name="content"><see cref="IContentBase"/> to add property value to</param> /// <param name="propertyTypeAlias">Alias of the property to save the value on</param> /// <param name="value">The <see cref="HttpPostedFileWrapper"/> containing the file that will be uploaded</param> public static void SetValue(this IContentBase content, string propertyTypeAlias, HttpPostedFileWrapper value) { // Ensure we get the filename without the path in IE in intranet mode // http://stackoverflow.com/questions/382464/httppostedfile-filename-different-from-ie var fileName = value.FileName; if (fileName.LastIndexOf(@"\") > 0) fileName = fileName.Substring(fileName.LastIndexOf(@"\") + 1); var name = IOHelper.SafeFileName(fileName); if (string.IsNullOrEmpty(name) == false) SetFileOnContent(content, propertyTypeAlias, name, value.InputStream); }
public async Task<ActionResult> Index(IndexViewModel model, HttpPostedFileWrapper upload) { Console.WriteLine(ModelState); if (ModelState.IsValid) { var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); user.FullName = model.FullName; if (upload != null && upload.ContentLength > 0 && upload.ContentLength < 8*1024*1024 && upload.ContentType.Contains("image/")) { var avatar = new FileModel { FileName = Guid.NewGuid() + Path.GetExtension(upload.FileName), FileType = FileType.Avatar, ContentType = upload.ContentType }; using (var reader = new BinaryReader(upload.InputStream)) { avatar.Content = reader.ReadBytes(upload.ContentLength); } user.Avatar = avatar; } var result = await UserManager.UpdateAsync(user); if (result.Succeeded) { return RedirectToAction("Index"); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); }
public void update(HttpPostedFileWrapper file, FormCollection fc) { Ads prc = new Ads(); if (Request.Params["IdUpdate"].Length > 0) { int id = int.Parse(Request.Params["IdUpdate"]); prc = _adsService.GetById(id); string url = prc.Image; if (Request.Params["NameAds"].Length > 0) { if (file != null) { var allowedExtensions = new[] { ".JPG", ".PNG", ".JPEG", ".GIF" }; var fileName = Path.GetFileName(file.FileName); //getting only file name(ex-ganesh.jpg) var ext = (Path.GetExtension(file.FileName)).ToUpper(); //getting the extension(ex-.jpg) if (allowedExtensions.Contains(ext)) //check what type of extension { string name = Path.GetFileNameWithoutExtension(fileName); //getting file name without extension string myfile = UnitilHelper.convertToUnSign(name) + DateTime.Now.Millisecond + ext; //appending the name with id string path = System.IO.Path.Combine(Server.MapPath("/Upload"), myfile); url = "Upload/" + myfile; file.SaveAs(path); } } prc.Name = fc["NameAds"]; prc.URL = fc["Url"]; prc.IsShow = fc["optionsRadios"] == "SetHot" ? true : false; prc.Image = url; _adsService.UpdateAds(prc); _unitOfWork.SaveChanges(); } } Response.Redirect("Index"); }
public ActionResult addDemography(int courseID, string callback, HttpPostedFileWrapper demographyImage) { ajaxReturnData data = new ajaxReturnData(); try { using (ApplicationDbContext DB = new ApplicationDbContext()) { SchoolCourse course = DB.schoolCourses.Where(c => c.id == courseID).FirstOrDefault(); if (demographyImage != null && demographyImage.ContentLength > 0) { string path = "/content/images/uploads/courses/" + course.id; bool exists = Directory.Exists(Server.MapPath(path)); if (!exists) { Directory.CreateDirectory(Server.MapPath(path)); } path = path + "/demographyImage" + Path.GetExtension(demographyImage.FileName); demographyImage.SaveAs(Server.MapPath(path)); course.demographyImage = path; DB.SaveChanges(); } } if (string.IsNullOrEmpty(callback)) { data.statusCode = (int)statusCodes.success; } else { data.statusCode = (int)statusCodes.successRun; data.callback = callback; } return Json(data); } catch (Exception ex) { data.statusCode = (int)statusCodes.fail; data.message = "Failed to add demo image; " + ex.Message; return Json(data); } }
public ActionResult editCourseGeneral(string name, int type, string editCourseIntroduction, HttpPostedFileWrapper introductionImage, string callback, int courseID, string languageCode = "en" ) { ajaxReturnData data = new ajaxReturnData(); SchoolCourse course = new SchoolCourse(); try { using (ApplicationDbContext DB = new ApplicationDbContext()) { course = DB.schoolCourses.Where(sc => sc.id == courseID).FirstOrDefault(); course.type = type; DB.SaveChanges(); if (introductionImage != null && introductionImage.ContentLength > 0) { string path = "/content/images/uploads/courses/" + course.id; bool exists = Directory.Exists(Server.MapPath(path)); if (!exists) { Directory.CreateDirectory(Server.MapPath(path)); } path = path + "/introductionImage" + Path.GetExtension(introductionImage.FileName); introductionImage.SaveAs(Server.MapPath(path)); course.introductionImage = path; DB.Entry(course).Property(l => l.introductionImage).IsModified = true; } course.addContent(DB, "name",name); course.addContent(DB, "courseIntroduction", editCourseIntroduction); DB.SaveChanges(); } if (string.IsNullOrEmpty(callback)) { data.statusCode = (int)statusCodes.success; } else { data.statusCode = (int)statusCodes.successRun; data.callback = callback; } data.message = "course updated"; return Json(data); } catch (Exception ex) { data.statusCode = (int)statusCodes.fail; data.message = "Failed to retrieve course; " + ex.Message; return Json(data); } }
public ActionResult addCourse(string callback, int schoolID, int type, string name, string courseIntroduction, HttpPostedFileWrapper introductionImage) { ajaxReturnData data = new ajaxReturnData(); try { using (ApplicationDbContext DB = new ApplicationDbContext()) { SchoolCourse sc = new SchoolCourse(); sc.schoolID = schoolID; sc.type = type; DB.schoolCourses.Add(sc); sc.features = new CourseFeatures(); DB.SaveChanges(); sc.addContent(DB, "name", name); sc.addContent(DB, "courseIntroduction", courseIntroduction); if (introductionImage != null && introductionImage.ContentLength > 0) { string path = "/content/images/uploads/courses/" + sc.id; bool exists = Directory.Exists(Server.MapPath(path)); if (!exists) { Directory.CreateDirectory(Server.MapPath(path)); } path = path + "/introductionImage" + Path.GetExtension(introductionImage.FileName); introductionImage.SaveAs(Server.MapPath(path)); sc.introductionImage = path; DB.Entry(sc).Property(l => l.introductionImage).IsModified = true; DB.SaveChanges(); } } if (string.IsNullOrEmpty(callback)) { data.statusCode = (int)statusCodes.success; } else { data.statusCode = (int)statusCodes.successRun; data.callback = callback; } data.message = "course added"; return Json(data); } catch (Exception ex) { data.statusCode = (int)statusCodes.fail; data.message = "Failed to add course; " + ex.Message; return Json(data); } }
public void Insert(FormCollection fc, HttpPostedFileWrapper file) { if (file != null && fc["nametype"].ToString() != "") { ProjectType _pro = new ProjectType(); var allowedExtensions = new[] { ".JPG", ".PNG", ".JPEG", ".GIF" }; var fileName = Path.GetFileName(file.FileName); //getting only file name(ex-ganesh.jpg) var ext = (Path.GetExtension(file.FileName)).ToUpper(); //getting the extension(ex-.jpg) if (allowedExtensions.Contains(ext)) //check what type of extension { string name = Path.GetFileNameWithoutExtension(fileName); //getting file name without extension string myfile = UnitilHelper.convertToUnSign(name) + DateTime.Now.Millisecond + ext; //appending the name with id string path = System.IO.Path.Combine(Server.MapPath("/Upload"), myfile); string url = "Upload/" + myfile; try { file.SaveAs(path); _pro.NameType = fc["nametype"].ToString(); _pro.Keyword = fc["Keyword"].ToString(); _pro.MetaDescription = fc["MetaDescription"].ToString(); _pro.Description = fc["description"].ToString() == "" ? "Đang cập nhật" : fc["description"].ToString(); _pro.Image = url; _pro.IsDeleted = false; _projectType.AddProjectType(_pro); _unitOfWork.SaveChanges(); } catch { } } } Response.Redirect("Index"); }