public IActionResult CreatePhoto(int?productId, string title, IFormFile image) { var model = new Picture { ProductId = productId, Title = title }; if (image != null && image.Length > 0) { var path = Path.GetExtension(image.FileName); var photoName = Guid.NewGuid() + path; var upload = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/img/product/" + photoName); var stream = new FileStream(upload, FileMode.Create); image.CopyTo(stream); model.ImageUrl = photoName; } var result = _pictureService.Create(model); if (result.Success) { TempData["message"] = result.Message; return(RedirectToAction(nameof(CreatePhoto))); } else { TempData["message"] = result.Message; return(RedirectToAction(nameof(CreatePhoto))); } }
public IActionResult AddPicture([FromBody] PictureModel pictureModel) { var BearToken = Request.Headers["Authorization"][0]; string tokenString = BearToken.Split(" ")[1]; JwtSecurityTokenHandler jsth = new JwtSecurityTokenHandler(); JwtSecurityToken jst = jsth.ReadJwtToken(tokenString); var owerName = jst.Claims.ToList()[0].Value; User u = _userService.GetByName(owerName); Picture picture = new Picture { PicName = pictureModel.picname, PicFileName = pictureModel.fileName, Catalogue = (Catalogue)pictureModel.catalogue, Visible = pictureModel.display, UserId = u.Id, UpLoadTime = DateTime.Now.ToString("yyyyMMdd") }; _iPictureService.Create(picture); Startup.UploadUser.Add(u.UserName); Startup.UpLoadNum--; return(Ok(new { picture.PicFileName, picture.PicName })); }
public JsonResult Upload() { JsonResult result = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, ContentType = "text/html", }; long productID = Request.Form["productID"] == null ? 0 : Convert.ToInt64(Request.Form["productID"]); try { var pics = GetUploadPictures(productID).ToArray(); if (!pics.Any()) { result.Data = new { success = false } } ; else { _pictureService.Create(pics); if (productID != 0) { Service.Create(pics); } var first = pics.FirstOrDefault(); var fullpath = Path.Combine(ftp, first.Path, _pictureService.GetName(first, MallSize)); result.Data = new { success = true, Id = first.ID != null ? first.ID.Value : 0, MallName = fullpath, OriginName = first.OriginName, Name = first.Name, Path = first.Path, IsFirst = first.IsFirst }; } return(result); } catch (PicTypeException e) { result.Data = new { success = false, message = string.Format(PicTypeError, e.pic.Name) }; return(result); } catch (PicSizeException e) { result.Data = new { success = false, message = string.Format(PicSizeError, e.pic.Name) }; return(result); } catch (Exception e) { result.Data = new { success = false, message = e.Message }; return(result); } }
public ActionResult Edit(EditPerformerViewModel model, int[] selectedCategories, HttpPostedFileBase loadImage) { if (!(bool)Session["isPerformer"] || !(bool)Session["adminStatus"]) { return(View("~/Views/Error/Forbidden.cshtml")); } if (!ModelState.IsValid) { return(View(model)); } if (ReferenceEquals(selectedCategories, null)) { return(RedirectToAction("Edit", new { message = "At least one category is required", company = model.Company, info = model.Info, phoneNumber = model.PhoneNumber })); } PictureViewModelBLL picture = null; if (!ReferenceEquals(loadImage, null)) { byte[] image; using (var binaryReader = new BinaryReader(loadImage.InputStream)) { image = binaryReader.ReadBytes(loadImage.ContentLength); } picture = new PictureViewModelBLL { Image = image }; _pictureService.Create(image); _unitOfWork.Save(); } ClientViewModelBLL client = _userService.FindById(User.Identity.GetUserId <int>()); Mapper.Initialize(cfg => cfg.CreateMap <EditPerformerViewModel, ClientViewModelBLL>() .ForMember("Name", opt => opt.MapFrom(c => client.Name)) .ForMember("CategoriesBll", opt => opt.MapFrom(c => c.Categories)) .ForMember("PictureId", opt => opt.MapFrom(c => _pictureService.FindByBytes(picture.Image).Value)) ); Mapper.Map(model, client); _userService.Update(client, selectedCategories); _unitOfWork.Save(); return(RedirectToAction("Details", new { id = client.Id })); }
public ActionResult BecomePerformer(BecomePerformerViewModel model, int[] selectedCategories, HttpPostedFileBase loadImage) { if ((bool)Session["isPerformer"] && (bool)Session["adminStatus"]) { return(View("~/Views/Error/Forbidden.cshtml")); } if (!ModelState.IsValid) { return(View(model)); } if (selectedCategories == null) { ModelState.AddModelError("", "At least one category is required"); GetCategoriesList(); return(View(model)); } PictureViewModelBLL picture = null; if (!ReferenceEquals(loadImage, null)) { byte[] image; using (var binaryReader = new BinaryReader(loadImage.InputStream)) { image = binaryReader.ReadBytes(loadImage.ContentLength); } picture = new PictureViewModelBLL { Image = image }; _pictureService.Create(image); _unitOfWork.Save(); } ClientViewModelBLL client = _userService.FindById(User.Identity.GetUserId <int>()); Mapper.Initialize(cfg => cfg.CreateMap <BecomePerformerViewModel, ClientViewModelBLL>() .ForMember("RegistrationDate", opt => opt.MapFrom(c => DateTime.Today)) .ForMember("IsPerformer", opt => opt.MapFrom(c => true)) .ForMember("AdminStatus", opt => opt.MapFrom(c => false)) .ForMember("Rating", opt => opt.MapFrom(c => 0)) .ForMember("PictureId", opt => opt.MapFrom(c => _pictureService.FindByBytes(picture.Image).Value)) ); Mapper.Map(model, client); _userService.Update(client, selectedCategories); _unitOfWork.Save(); return(RedirectToAction("Index")); }
public async Task <IActionResult> LoadPicturesFromAPI() { // get all from api var pictures = await _pictureProvider.GetAll(); pictures = await _pictureProvider.FetchDetails(pictures); // clear and save await _pictureService.RemoveAll(); await _pictureService.Create(pictures); return(Ok()); }
// UploadPicture <albumName> <pictureTitle> <pictureFilePath> public string Execute(string[] data) { string albumName = data[0]; string pictureTitle = data[1]; string pictureFilePath = data[2]; AlbumDto albumDTO = albumService.ByName <AlbumDto>(albumName); if (albumDTO == null) { throw new ObjectNotFoundException(typeof(Album).Name, albumName); } var picture = pictureService.Create(albumDTO.Id, pictureTitle, pictureFilePath); return(String.Format(SuccessMessage, pictureTitle, albumName)); }
public IHttpActionResult Post([FromBody] CreatePictureViewModel model) { if (model == null) { return(BadRequest()); } Picture picture = new Picture { Path = model.Path }; pictureService.Create(picture); return(Ok()); }
public IActionResult MultiplePhotoEdit(Picture model, IEnumerable <IFormFile> images) { foreach (var image in images) { var path = Path.GetExtension(image.FileName); var photoName = Guid.NewGuid() + path; var upload = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/img/product/" + photoName); var stream = new FileStream(upload, FileMode.Create); image.CopyTo(stream); model.ImageUrl = photoName; _pictureService.Create(model); } return(RedirectToAction(nameof(Index))); }
public ActionResult Create(CreateOrderViewModel order, HttpPostedFileBase loadImage) { if (ModelState.IsValid) { PictureViewModelBLL picture = null; if (!ReferenceEquals(loadImage, null)) { byte[] image; using (var binaryReader = new BinaryReader(loadImage.InputStream)) { image = binaryReader.ReadBytes(loadImage.ContentLength); } picture = new PictureViewModelBLL { Image = image }; _pictureService.Create(image); _unitOfWork.Save(); } Mapper.Initialize(cfg => cfg.CreateMap <CreateOrderViewModel, OrderViewModelBLL>() .ForMember("CategoryId", opt => opt.MapFrom(c => _categoryService.FindByName(c.Category).Id)) .ForMember("StatusId", opt => opt.MapFrom(c => 1)) .ForMember("AdminStatus", opt => opt.MapFrom(c => false)) .ForMember("UploadDate", opt => opt.MapFrom(c => DateTime.Now)) .ForMember("UserId", opt => opt.MapFrom(c => User.Identity.GetUserId <int>())) .ForMember("PictureId", opt => opt.MapFrom(c => _pictureService.FindByBytes(picture.Image).Value)) ); OrderViewModelBLL orderDto = Mapper.Map <CreateOrderViewModel, OrderViewModelBLL>(order); OperationDetails operationDetails = _orderService.Create(orderDto); _unitOfWork.Save(); if (operationDetails.Succedeed) { return(RedirectToAction("Index")); } ModelState.AddModelError(operationDetails.Property, operationDetails.Message); } ModelState.AddModelError("", "Creation error"); ViewBag.Category = new SelectList(_categoryService.GetAll(), "Name", "Name"); ViewBag.DefaultPath = $"data: image/png; base64, {Convert.ToBase64String(System.IO.File.ReadAllBytes(Server.MapPath(DefaultImageName)))}"; return(View(order)); }
public JsonResult UploadPic(int index) { var picFile = Request.Files["Pic" + index]; byte[] buffer = new byte[picFile.ContentLength]; picFile.InputStream.Read(buffer, 0, picFile.ContentLength); var pic = new PictureResource() { OriginName = Path.GetFileName(picFile.FileName), Content = buffer, }; pic.Name = GetHashName(pic.OriginName); pic.Path = MakeCoverPicPath(0); NewsContentPictureService.Create(pic); return(new JsonResult() { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = new { success = true, path = Path.Combine(ftp, pic.Path, pic.Name), name = pic.OriginName } }); }
public JsonResult CreatePic() { var resources = GetUploadResource(); PictureResource pic = resources.Select(item => new PictureResource(item)).FirstOrDefault(); pic.Path = MakePath(pic); pic.Name = GetHashName(pic.OriginName); ResourcePictureService.Create(pic); Service.Create(pic); return(new JsonResult() { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = new { success = true, resourceID = pic.ID, name = pic.OriginName, path = System.IO.Path.Combine(ftp, pic.Path, GetName(pic, ItemSize)), size = pic.Size }, }); }
/// <summary> /// 统一处理图片上传工作 /// </summary> /// <param name="res">需要返回的操作结果</param> /// <param name="picType">带处理的图片类型</param> /// <returns>操作结果</returns> public JsonResult DoUpload(int picType) { JsonResult result = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, ContentType = "text/html" }; try { var pics = GetUploadPictures(picType).ToArray(); if (!pics.Any()) { result.Data = new { success = false, Message = "文件列表为空" } } ; else { List <BannerPicture> _List = new List <BannerPicture>(); foreach (var item in pics.ToList()) { item.Name = DateTime.Now.ToString("yyMMdd_HHmmss_") + item.Name; _pictureService.Create(item); svc.Create(item); var fullpath = Path.Combine(ftp, item.Path, item.Name); BannerPicture _item = item; _item.Path = fullpath; _List.Add(_item); } //清空Content,否则反序列化时会因数据太大而失败 foreach (var item in _List) { item.Content = null; } result.Data = new { success = true, picList = _List }; } return(result); } catch (PicTypeException e) { //文件格式不正确,提示错误时,需还原成本地文件名称,去除区分同名文件所加上的时间戳字符串 result.Data = new { success = false, Message = string.Format(PicTypeError, e.pic.Name.Substring(14)) }; return(result); } catch (PicSizeException e) { //文件大小超出,提示错误时,需还原成本地文件名称,去除区分同名文件所加上的时间戳字符串 result.Data = new { success = false, Message = string.Format(PicSizeError, e.pic.Name.Substring(14)) }; return(result); } catch (Exception e) { result.Data = new { success = false, Message = e.Message }; return(result); } }
public async Task <IActionResult> Add(int id, PicturesFormModel model) { var creatorUserName = await this.advertisement.CreatorUserName(id); var currentUserName = this.User.Identity.Name; if (creatorUserName != currentUserName) { TempData.AddErrorMessage(WebConstants.ErrorMessageNotAllowedToPage); return(RedirectToAction(nameof(AdvertisementsController.All), WebConstants.AdvertisementsControllerName)); } if (!ModelState.IsValid) { model.AdvertisementId = id; return(View(model)); } var firstUrlEnding = model.UrlPathFirst.Trim().Substring(model.UrlPathFirst.Length - 4); var secondUrlEnding = model.UrlPathSecond.Trim().Substring(model.UrlPathSecond.Length - 4); var thirdUrlEnding = model.UrlPathThird.Trim().Substring(model.UrlPathThird.Length - 4); var correctPicture = true; if (firstUrlEnding != WebConstants.EndsWithJpg && firstUrlEnding != WebConstants.EndsWithPng) { correctPicture = false; model.UrlPathFirst = DataConstants.ImgDefoutNotFound; } if (secondUrlEnding != WebConstants.EndsWithJpg && secondUrlEnding != WebConstants.EndsWithPng) { correctPicture = false; model.UrlPathSecond = DataConstants.ImgDefoutNotFound; } if (thirdUrlEnding != WebConstants.EndsWithJpg && thirdUrlEnding != WebConstants.EndsWithPng) { correctPicture = false; model.UrlPathThird = DataConstants.ImgDefoutNotFound; } await picture.Create( model.UrlPathFirst, true, model.UrlPathSecond, false, model.UrlPathThird, false, id); if (correctPicture) { TempData.AddSuccessMessage(WebConstants.SuccessMessagePictureAdd); } else { TempData.AddErrorMessage(WebConstants.ErrorMessagePicutureWithNoPngOrJpg); } return(RedirectToAction(nameof(AdvertisementsController.Details), WebConstants.AdvertisementsControllerName, new { id = id })); }