示例#1
0
        public async Task <IActionResult> ChangeUserPhoto(Guid userId, [FromForm] PhotoForProfileDto photoForProfileDto)
        {
            if (userId.ToString() != User.FindFirst(ClaimTypes.NameIdentifier).Value)
            {
                return(Unauthorized("شما اجازه تغییر تصویر را ندارید"));
            }

            var userFromDb = await _db.UserRepository.GetByIdAsync(userId);

            var file = photoForProfileDto.File;

            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, stream),
                        Transformation = new Transformation().Width(250).Height(250).Crop("fill").Gravity("face")
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

            photoForProfileDto.Url = uploadResult.Url.ToString();

            photoForProfileDto.PublicId = uploadResult.PublicId;


            var oldPhoto = await _db.PhotoRepository.GetAsync(p => p.UserId == userId && p.IsMain);


            // اگر کاربر عکسی در کلودینری   داشت پاکش کن  که حجم الکی نگیره
            if (oldPhoto.PublicId != null && oldPhoto.PublicId != "0")
            {
                var deleteParam  = new DeletionParams(oldPhoto.PublicId);
                var deleteResult = _cloudinary.Destroy(deleteParam);
            }

            _mapper.Map(photoForProfileDto, oldPhoto);

            _db.PhotoRepository.Update(oldPhoto);

            //await _db.PhotoRepository.InsertAsync(photo);

            if (await _db.SaveAsync())
            {
                var photoForReturn = _mapper.Map <PhotoForReturnProfileDto>(oldPhoto);
                return(CreatedAtRoute("GetPhoto", routeValues: new { id = oldPhoto.Id }, photoForReturn));
            }
            else
            {
                return(BadRequest("دوبار تلاش کنید"));
            }
        }
        public async Task <IActionResult> ChangeUserPhoto(string userId, [FromForm] PhotoForProfileDto photoForProfileDto)
        {
            if (userId != User.FindFirst(ClaimTypes.NameIdentifier).Value)
            {
                return(Unauthorized("شما اجازه تغییر تصویر این کاربر را ندارید"));
            }
            //var UserFromRepo = await _db.UserReosiroty.GetByIDAsync(userId);

            var file         = photoForProfileDto.File;
            var uploadresult = new ImageUploadResult();

            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream())
                {
                    var uploaparams = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, stream),
                        Transformation = new Transformation().Width(150).Height(150).Crop("fill").Gravity("face")
                    };
                    uploadresult = _cloudinary.Upload(uploaparams);
                }

                photoForProfileDto.Url      = uploadresult.Uri.ToString();
                photoForProfileDto.PublicId = uploadresult.PublicId;

                var oldphoto = await _db.PhotoRepository.GetAsync(p => p.UserId == userId && p.IsMain);

                if (oldphoto.PublicId != null && oldphoto.PublicId != "0")
                {
                    var deleteparams = new DeletionParams(oldphoto.PublicId);
                    var deleteresult = _cloudinary.Destroy(deleteparams);
                    //if (deleteresult.Result.ToLower()=="ok")
                    //{

                    //}
                }
                _mapper.Map(photoForProfileDto, oldphoto);


                _db.PhotoRepository.Update(oldphoto);
                if (await _db.SaveAsync())
                {
                    var photoforReturn = _mapper.Map <PhotoForReturnProfileDto>(oldphoto);
                    CreatedAtRoute("GetPhoto", new { id = oldphoto.ID }, photoforReturn);
                    return(Ok());
                }
                else
                {
                    return(BadRequest("خطایی در آپلود دوباره امتحان کنید"));
                }
            }
            return(BadRequest("خطایی در آپلود دوباره امتحان کنید"));
        }
        public async Task <IActionResult> ChangeUserPhoto(string userId, [FromForm] PhotoForProfileDto photoForProfileDto)
        {
            //var userFromRepo = await _db.UserRepository.GetByIdAsync(userId);

            // var uplaodRes = _uploadService.UploadToCloudinary(photoForProfileDto.File);

            var uplaodRes = await _uploadService.UploadFile(
                photoForProfileDto.File,
                userId,
                _env.WebRootPath,
                $"{Request.Scheme ?? ""}://{Request.Host.Value ?? ""}{Request.PathBase.Value ?? ""}",
                "Files\\Pic\\Profile\\" + DateTime.Now.Year + "\\" + DateTime.Now.Month + "\\" + DateTime.Now.Day
                );

            if (uplaodRes.Status)
            {
                photoForProfileDto.Url = uplaodRes.Url;
                if (uplaodRes.LocalUploaded)
                {
                    photoForProfileDto.PublicId = "1";
                }
                else
                {
                    photoForProfileDto.PublicId = uplaodRes.PublicId;
                }


                var oldphoto = await _db.PhotoRepository.GetAsync(p => p.UserId == userId && p.IsMain);

                if (oldphoto.PublicId != "2")
                {
                    if (oldphoto.PublicId != null && oldphoto.PublicId != "0" && oldphoto.PublicId != "1")
                    {
                        _uploadService.RemoveFileFromCloudinary(oldphoto.PublicId);
                    }
                    if (oldphoto.PublicId == photoForProfileDto.PublicId && photoForProfileDto.Url.Split('/').Last() != oldphoto.Url.Split('/').Last())
                    {
                        _uploadService.RemoveFileFromLocal(
                            oldphoto.Url.Split('/').Last(),
                            _env.WebRootPath,
                            _utilities.FindLocalPathFromUrl(oldphoto.Url).Replace("wwwroot\\", ""));
                    }
                    if (oldphoto.PublicId == "1" && photoForProfileDto.PublicId != "1")
                    {
                        _uploadService.RemoveFileFromLocal(
                            oldphoto.Url.Split('/').Last(),
                            _env.WebRootPath,
                            _utilities.FindLocalPathFromUrl(oldphoto.Url).Replace("wwwroot\\", ""));
                    }
                }

                _mapper.Map(photoForProfileDto, oldphoto);

                _db.PhotoRepository.Update(oldphoto);

                if (await _db.SaveAsync())
                {
                    var photoForReturn = _mapper.Map <PhotoForReturnProfileDto>(oldphoto);
                    return(CreatedAtRoute("GetPhoto", routeValues: new { v = HttpContext.GetRequestedApiVersion().ToString(), id = oldphoto.Id }, value: photoForReturn));
                }
                else
                {
                    return(BadRequest("خطایی در اپلود دوباره امتحان کنید"));
                }
            }
            else
            {
                return(BadRequest(uplaodRes.Message));
            }
        }
        public async Task <IActionResult> ChangeUserPhoto(string userId, [FromForm] PhotoForProfileDto photoForProfileDto)
        {
            //var userFromRepo = await _db.UserRepository.GetByIdAsync(userId);

            // var uplaodRes = _uploadService.UploadToCloudinary(photoForProfileDto.File);

            var uplaodRes = await _uploadService.UploadProfilePic(
                photoForProfileDto.File,
                userId,
                _env.WebRootPath,
                string.Format("{0}://{1}{2}", Request.Scheme ?? "", Request.Host.Value ?? "", Request.PathBase.Value ?? "")
                );

            if (uplaodRes.Status)
            {
                photoForProfileDto.Url = uplaodRes.Url;
                if (uplaodRes.LocalUploaded)
                {
                    photoForProfileDto.PublicId = "1";
                }
                else
                {
                    photoForProfileDto.PublicId = uplaodRes.PublicId;
                }



                var oldphoto = await _db.PhotoRepository.GetAsync(p => p.UserId == userId && p.IsMain);

                if (oldphoto.PublicId != null && oldphoto.PublicId != "0" && oldphoto.PublicId != "1")
                {
                    _uploadService.RemoveFileFromCloudinary(oldphoto.PublicId);
                }
                if (oldphoto.PublicId == photoForProfileDto.PublicId && photoForProfileDto.Url.Split('/').Last() != oldphoto.Url.Split('/').Last())
                {
                    _uploadService.RemoveFileFromLocal(oldphoto.Url.Split('/').Last(), _env.WebRootPath, "Files\\Pic\\Profile");
                }

                if (oldphoto.PublicId == "1" && photoForProfileDto.PublicId != "1")
                {
                    _uploadService.RemoveFileFromLocal(oldphoto.Url.Split('/').Last(), _env.WebRootPath, "Files\\Pic\\Profile");
                }

                _mapper.Map(photoForProfileDto, oldphoto);

                _db.PhotoRepository.Update(oldphoto);

                if (await _db.SaveAsync())
                {
                    var photoForReturn = _mapper.Map <PhotoForReturnProfileDto>(oldphoto);
                    return(CreatedAtRoute("GetPhoto", routeValues: new { id = oldphoto.Id }, value: photoForReturn));
                }
                else
                {
                    return(BadRequest("خطایی در اپلود دوباره امتحان کنید"));
                }
            }
            else
            {
                return(BadRequest(uplaodRes.Message));
            }
        }