Пример #1
0
        public ActionResult Upload(UploadPhotoViewModel model, int id)
        {
            if (model != null && ModelState.IsValid)
            {
                foreach (var file in model.Files)
                {
                    if (file.ContentLength > 0)
                    {
                        var fileName = Path.GetFileName(file.FileName);
                        var folderPath = Server.MapPath("~/Images/Upload/" + id);
                        string imagePath = folderPath + "/" + fileName;

                        if (!Directory.Exists(folderPath))
                        {
                            DirectoryInfo di = Directory.CreateDirectory(folderPath);
                        }

                        file.SaveAs(imagePath);

                        var photo = new Photo();
                        photo.Address = "/Images/Upload/" + id + "/" + fileName;
                        photo.AnimalId = id;
                        photo.Animal = this.animal.GetById(id).FirstOrDefault();
                        this.photos.AddNew(photo);
                    }
                }
                return this.RedirectToAction("Details", "Animals", new { area = "", id = id });
            }
            else
            {
                return this.View();
            }
        }
Пример #2
0
        public ActionResult Upload(UploadPhotoViewModel model, int id)
        {
            if (model != null && ModelState.IsValid)
            {
                foreach (var file in model.Files)
                {
                    if (file.ContentLength > 0)
                    {
                        var    fileName   = Path.GetFileName(file.FileName);
                        var    folderPath = Server.MapPath("~/Images/Upload/" + id);
                        string imagePath  = folderPath + "/" + fileName;

                        if (!Directory.Exists(folderPath))
                        {
                            DirectoryInfo di = Directory.CreateDirectory(folderPath);
                        }

                        file.SaveAs(imagePath);

                        var photo = new Photo();
                        photo.Address  = "/Images/Upload/" + id + "/" + fileName;
                        photo.AnimalId = id;
                        photo.Animal   = this.animal.GetById(id).FirstOrDefault();
                        this.photos.AddNew(photo);
                    }
                }
                return(this.RedirectToAction("Details", "Animals", new { area = "", id = id }));
            }
            else
            {
                return(this.View());
            }
        }
 public sealed override void Init(object obj = null)
 {
     App.Configuration.Initial(this);
     NavigationPage.SetHasNavigationBar(this, false);
     _model         = new UploadPhotoViewModel();
     BindingContext = _model;
     Initialization();
 }
Пример #4
0
        public ActionResult UploadPhoto(UploadPhotoViewModel model, HttpPostedFileBase photo)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            photo.SaveAs(Path.Combine(Server.MapPath("~/Photos"), photo.FileName));
            return(RedirectToAction("Index"));
        }
        public async Task <IActionResult> ChangeBackground(UploadPhotoViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            model = await SavePhoto(model);

            return(Ok(model));
        }
Пример #6
0
 public static BllPhoto ToBllPhoto(this UploadPhotoViewModel photo, int userId)
 {
     return(new BllPhoto()
     {
         Name = photo.Name,
         Image = ToByteArray(photo.ImageFile),
         Description = photo.Description,
         Tags = ToTags(photo.Tags),
         UploadDate = DateTime.Now,
         UserLikes = new List <int>(0),
         UserId = userId
     });
 }
Пример #7
0
        //[HttpPost]//No any referencies -----> to Api
        //public IActionResult PostHerData(ICollection<IFormFile> files, int User_Id, NewsDataViewModels newsData, string img_comment, string hidd, string inp, [FromBody]string comment)
        //{
        //    //long size = files.Sum(f => f.Length);
        //    string mainFolder = _environment.ContentRootPath;
        //    int n = 0;
        //    string msg = "";
        //    bool success = false;

        //    IFormFile file = (files.ToList())[0];
        //    string filePath = "";

        //    string fileName = file?.FileName?.Replace(" ", "_").Replace("-", "_");
        //    if (file?.FileName != null)
        //    {
        //        int ii = fileName.LastIndexOf("\\");
        //        if (ii != -1)
        //        {
        //            fileName = fileName.Substring(ii + 1);
        //        }
        //    }

        //    int i = file.FileName.LastIndexOf(".");
        //    if (i == -1)
        //    {
        //        newsData.message = "It is not correct file name!!";
        //        //return Ok(new { count = files.Count, size, filePath });
        //        return View("HerUploadImage", newsData);
        //    }
        //    string ext = file.FileName.Substring(i + 1);


        //    //if (videos.Contains(ext))40---55
        //    //{
        //    string path1 = _environment.ContentRootPath + @"\wwwroot\Images\Heritage\63263cc2-119b-4ec5-9f4a-b33a30ecb74b.jpg";
        //    filePath = _environment.WebRootPath + @"\Images\Heritage\Temp\" + fileName;
        //    //}
        //    //if (images.Contains(ext))
        //    //{
        //    //    filePath = _environment.WebRootPath + @"\VideoFiles\Images\" + fileName;
        //    //}

        //    //if (file.Length > 0)
        //    //{
        //    using (var stream = new FileStream(filePath, FileMode.Create))
        //    {
        //        try
        //        {
        //            file.CopyTo(stream);
        //            //bool res = videoRepository.AddVideo(newsData, filePath);
        //            //string pathImg1 = heritageRepository.ModifyImageStrickt(filePath, 40, 55, "63263cc2-119b-4ec5-9f4a-b33a30ecb74b", imageFormat);
        //            //stream.Position = 0;
        //            n += 1;


        //        }
        //        catch (Exception ex)
        //        {
        //            msg += " There was problem to save file :  " + file?.FileName;
        //        }
        //    }
        //    //}
        //    //}
        //    HerRepData herRepData = heritageRepository.ModifyImageStrict(filePath, PHOTO_WIDTH, PHOTO_HEIGHT, "63263cc2-119b-4ec5-9f4a-b33a30ecb74b", imageFormat, ImageModificationsType.InDivCenter);
        //    herRepData.path = herRepData.path.Substring(herRepData.path.IndexOf("Images") - 1);

        //    if (n > 0)
        //    {
        //        msg += " File saved successfully.";
        //        success = true;
        //        return Json(new
        //        {
        //            success = success,
        //            message = msg,
        //            path = herRepData.path.ToLower(),
        //            height = herRepData?.size.Height,
        //            width = herRepData?.size.Width
        //        });
        //    }
        //    else
        //    {
        //        newsData.message = "There was not selected file!";
        //        //return Ok(new { count = files.Count, size, filePath });
        //        return View("HerUploadImage", newsData);
        //    }

        //}
        #endregion

        #region Permissions
        public IActionResult AskHerPermission(string ids, bool isEditable)
        {
            AppSettings appSettings = heritageRepository.GetAppSettings(_config);

            UploadPhotoViewModel model = new UploadPhotoViewModel();

            //CardIds cardIds = heritageRepository.GetLevelsAsIntList(id);
            //HeritageViewModel model = heritageRepository.GetHerEditModelByLevels(cardIds);

            //model.user_id = 2;
            //model.lName = "albert";
            return(View("AskHerPermission", model));
        }
Пример #8
0
        public ViewResult GetHerData_Image(string card_id)
        {
            UploadPhotoViewModel uploadPhotoViewModel = new UploadPhotoViewModel();
            s_strings            s_Strings            = heritageRepository.GetRootImageNamesByIds(card_id);

            uploadPhotoViewModel.rootHerImg  = s_Strings?.str1;
            uploadPhotoViewModel.rootHerName = s_Strings?.str2;
            List <InfoItem> InfoItems = heritageRepository.GetImageCommentListByIds(card_id);

            uploadPhotoViewModel.infoItemsStr = JsonConvert.SerializeObject(InfoItems);

            return(View("HerUploadImage_Data", uploadPhotoViewModel));
        }
        private async Task <UploadPhotoViewModel> SavePhoto(UploadPhotoViewModel model)
        {
            var file = model.Files;

            if (model.Files.Length > 0)
            {
                var path = Path.Combine(environment.WebRootPath, "images");

                using (var fs = new FileStream(Path.Combine(path, file.FileName), FileMode.Create))
                {
                    await file.CopyToAsync(fs);
                }
                model.Source = $"images/{file.FileName}";
            }
            return(model);
        }
Пример #10
0
        public async Task <IActionResult> Create([Bind("IndividualId,File,Comment,Magnification")] UploadPhotoViewModel uploadPhoto)
        {
            if (uploadPhoto == null)
            {
                return(NotFound());
            }
            //var client = new AmazonS3Client(_accessKey, _secretKey, Amazon.RegionEndpoint.SAEast1);

            //var contentDisposition = ContentDispositionHeaderValue.Parse(uploadPhoto.File.ContentDisposition);

            //var filename = contentDisposition.FileName.Trim('"');

            //var stream = uploadPhoto.File.OpenReadStream();

            using (var stream = new FileStream(Path.Combine(Directory.GetCurrentDirectory(),
                                                            "DB", uploadPhoto.File.FileName), FileMode.Create))
            {
                await uploadPhoto.File.CopyToAsync(stream).ConfigureAwait(false);
            }

            //var request = new PutObjectRequest
            //{
            //    BucketName = _bucket,
            //    Key = uploadPhoto.IndividualId.ToString()+"/"+filename,
            //    InputStream = stream,
            //    CannedACL = S3CannedACL.Private
            //};

            //var response = await client.PutObjectAsync(request);

            var photo = new Photo
            {
                IndividualId  = uploadPhoto.IndividualId,
                Key           = uploadPhoto.File.FileName,
                Comment       = uploadPhoto.Comment,
                Magnification = uploadPhoto.Magnification
            };

            if (ModelState.IsValid)
            {
                _context.Add(photo);
                await _context.SaveChangesAsync().ConfigureAwait(false);

                return(RedirectToAction("Index"));
            }
            return(View(photo));
        }
Пример #11
0
        public ActionResult UploadPhoto(UploadPhotoViewModel model, HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
            {
                using (var reader = new BinaryReader(file.InputStream)) {
                    model.Photo = reader.ReadBytes(file.ContentLength);
                }

                var userId = User.Identity.GetUserId();
                var user   = db.Users.Where(u => u.Id == userId).First();
                user.Photo = model.Photo;

                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();

                return(RedirectToAction("RedirectUser", "Home"));
            }

            return(View(model));
        }
Пример #12
0
 public UploadPhotoPage(UserFirstUpdate user, bool error = false, string message = "")
 {
     InitializeComponent();
     App.Configuration.InitialAsync(this);
     NavigationPage.SetHasNavigationBar(this, false);
     _media = DependencyService.Get <IMedia>();
     _devicePermissionServices = DependencyService.Get <IDevicePermissionServices>();
     _model         = new UploadPhotoViewModel();
     _user          = user;
     BindingContext = _model;
     Initialization();
     _trackerPivotService = DependencyService.Get <ITrackerPivotService>();
     _helper = DependencyService.Get <IHelper>();
     if (error)
     {
         _model.SetActivityResource(showError: true,
                                    errorMessage: string.IsNullOrWhiteSpace(message.Trim())
                 ? message.Trim()
                 : _helper.ReturnMessage(message));
     }
 }
Пример #13
0
        // Users can only submit local files.
        public async Task <IActionResult> Create(UploadPhotoViewModel model) // This implementation because this is form file uploading.
        {
            if (model.PlaceId == -1 || !ModelState.IsValid)
            {
                return(BadRequest());
            }
            var place = context.Places.FirstOrDefault(p => p.Id == model.PlaceId);

            if (place == null)
            {
                return(NotFound());
            }
            if (place.PlacePhotos == null)
            {
                place.PlacePhotos = new List <PlacePhoto>();
            }
            var photo = new PlacePhoto {
                Place = place,
                IsGooglePlacesImage = false,
                FileName            = model.File.FileName
            };

            context.PlacePhotos.Add(photo);
            context.SaveChanges();
            var fileExt = model.File.ContentType.Split('/').Last();

            try {
                await S3Client.PutObjectAsync(new PutObjectRequest {
                    BucketName  = bucketName,
                    Key         = $"{photo.Id}-{model.File.FileName}",
                    InputStream = model.File.OpenReadStream()
                });
            } catch (Exception e) {
                return(StatusCode((int)HttpStatusCode.InternalServerError));
            }
            place.PlacePhotos.Add(photo);
            context.Places.Update(place);
            context.SaveChanges();
            return(Ok());
        }
Пример #14
0
        public async Task <ActionResult> UploadPhoto(UploadPhotoViewModel model)
        {
            if (model != null && model.Photo != null && model.Photo.Length > 0)
            {
                var dir = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "photos", model.WycieczkaId.ToString());


                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                var path = Path.Combine(dir, model.Photo.FileName);

                using (var stream = new FileStream(path, FileMode.Create))
                {
                    await model.Photo.CopyToAsync(stream);
                }
            }

            return(RedirectToAction("Details", new { id = model.WycieczkaId }));
        }
Пример #15
0
        public IActionResult Upload(UploadPhotoViewModel vm)
        {
            if (ModelState.IsValid)
            {
                string photoFileName = "";

                if (vm.Photo != null)
                {
                    photoFileName = this._photoFileProcessor.FileProcessor.SavePhoto(vm.Photo, "Photos"); //save photo in the folder
                }
                var photo = new Photo()
                {
                    Title        = vm.Title,
                    Path         = photoFileName,
                    UploaderId   = this._userSessionService.GetCurrentUserID(),
                    DateUploaded = DateTime.Now
                };

                this._photoFileProcessor.PhotoService.SavePhoto(photo); //save photo path in the database
                return(RedirectToAction("Index", "Home"));
            }

            return(View(vm));
        }
Пример #16
0
 public UploadPhotoPage(String category)
 {
     BindingContext = new UploadPhotoViewModel(this.Navigation, category);
     InitializeComponent();
 }
Пример #17
0
        public ActionResult UploadPhoto(UploadPhotoViewModel model, HttpPostedFileBase image = null)
        {
            if (ModelState.IsValid)
            {
                if (image != null)
                {
                    if (image.ContentLength < ConfigurationElements.MaxFileSize * ConfigurationElements.ModifierForMaxSize)
                    {
                        model.ImageMimeType = image.ContentType;
                        if (model.ImageMimeType.ToLower().Contains("image/jpeg"))
                        {
                            string userId = User.Identity.GetUserId();

                            _logger.Info("User {0} attempts to add a new photo", userId);

                            model.UniqueUserName = _userService.GetUniqueUserNameById(userId);

                            var request = new RequestEntity
                            {
                                PhotoName      = model.PhotoName,
                                UniqueUserName = model.UniqueUserName
                            };

                            if (!_photoService.CheckIfPhotoExists(request))
                            {
                                model.MiniatureImageData = new byte[image.ContentLength];

                                image.InputStream.Read(model.MiniatureImageData, 0, image.ContentLength);
                                model.MidSizeImageData = model.MiniatureImageData;
                                model.SourceImageData  = model.MiniatureImageData;

                                var uploadRequest = MapperHelper.GetValue <UploadPhotoViewModel, Photo>(model);
                                _photoService.UploadPhoto(uploadRequest);

                                _logger.Info("User {0} successfully added photo", userId);
                                TempData["ResultMessage"] = string.Format(SuccessMessages.SuccessfullyUploadedPhoto, model.PhotoName);

                                return(RedirectToAction("ViewPhoto", new { uniqueUserName = model.UniqueUserName, photoName = model.PhotoName }));
                            }
                            else
                            {
                                ModelState.AddModelError("AlreadyExists", "Photo with such name already exists in your collection");
                            }
                        }
                        else
                        {
                            ModelState.AddModelError("MimeType", "Wrong type, should be jpeg");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("Size", "The file is too big");
                    }
                }
                else
                {
                    ModelState.AddModelError("NoPic", "There is no photo");
                }
            }
            return(View(model));
        }
Пример #18
0
 public ActionResult UploadPhoto(UploadPhotoViewModel model)
 {
     return(View());
 }
Пример #19
0
 public ActionResult UploadPhoto(UploadPhotoViewModel photo)
 {
     photoService.Add(photo.ToBllPhoto(accountService.GetUserByLogin(User.Identity.Name).Id));
     return(RedirectToAction("Index", "Profile"));
 }
Пример #20
0
        public IActionResult PostHerImage(ICollection <IFormFile> files, int User_Id, UploadPhotoViewModel uploadData, string img_comment)
        {
            AppSettings appSettings = heritageRepository.GetAppSettings(_config);
            int         n           = 0;
            string      msg         = "";
            bool        success     = false;
            string      filePath    = "";

            if (files.Count == 0)
            {
                uploadData.message = "Select file for upload!";
                return(View("HerUploadImage", uploadData));
            }

            IFormFile file     = (files.ToList())[0];
            string    fileName = file?.FileName?.Replace(" ", "_").Replace("-", "_");

            if (file?.FileName != null)
            {
                int ii = fileName.LastIndexOf("\\");
                if (ii != -1)
                {
                    fileName = fileName.Substring(ii + 1);
                }
            }

            int i = file.FileName.LastIndexOf(".");

            if (i == -1)
            {
                uploadData.message = "It is not correct file name!!";
                return(View("HerUploadImage", uploadData));
            }
            //string user_name = "63263cc2-119b-4ec5-9f4a-b33a30ecb74b";//????????????   after when authentication
            //string user_name = userIdStr;//????????????   after when authentication
            //filePath = _environment.WebRootPath + @"\Images\Heritage\Temp\" + fileName;

            string folderPath = _environment.WebRootPath + @"\Images\Heritage\Temp\";

            filePath = folderPath + uploadData?.heritageIds + fileName;

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                try
                {
                    file.CopyTo(stream);
                    n += 1;
                }
                catch (Exception ex)
                {
                    msg += " There was problem to save file :  " + file?.FileName;
                }
            }
            HerRepData herRepData = heritageRepository.ModifyImageStrict(filePath, appSettings.IMAGE_WIDTH, appSettings.IMAGE_HEIGHT, appSettings.userIdStr, imageFormat, ImageModificationsType.WithGivenWidth);
            string     PATH       = herRepData?.path;

            herRepData.path = herRepData?.path?.Substring(herRepData.path.IndexOf("Images") - 1);

            if (!string.IsNullOrWhiteSpace(herRepData?.path))
            {
                bool retVal = heritageRepository.DeleteTempFolderFiles(folderPath);
            }

            if (n > 0 && herRepData.message == "")
            {
                uploadData.height = herRepData?.size.Height ?? 0;
                uploadData.width  = herRepData?.size.Width ?? 0;
                uploadData.path   = herRepData.path.ToLower();
                RetSimple retSimple = heritageRepository.UpdateDBWithImageInfo(uploadData);
                if (retSimple.message != "")
                {
                    uploadData.message = retSimple.message;
                    return(View("HerUploadImage_Data", uploadData));
                }

                msg    += " File saved successfully.";
                success = true;
                return(Json(new
                {
                    success = success,
                    message = msg,
                    path = herRepData.path.ToLower(),
                    height = herRepData?.size.Height,
                    width = herRepData?.size.Width,
                    img_comment = img_comment,
                    order_number = retSimple.Id,
                    card_ids = uploadData.heritageIds
                }));
            }
            else
            {
                uploadData.message = "There was not selected file! \n " + herRepData.message;
                //return Ok(new { count = files.Count, size, filePath });
                return(View("HerUploadImage_Data", uploadData));
            }
        }