Beispiel #1
0
        public async Task <IActionResult> ChangeUserPhoto(string userId, [FromForm] PhotoFromUserProfileDto photoFromUserProfileDto)
        {
            var file = photoFromUserProfileDto.File;
            //var uploadResult = await _uploadService.UploadProfileImageToCloudinary(file,userId);
            string baseUrl = string.Format($"{Request.Scheme ?? ""}://{Request.Host.Value ?? ""}{Request.PathBase.Value ?? ""}");

            //var uploadResult = await _uploadService.UploadProfileImageToLocal(file,userId,_env.WebRootPath,baseUrl);

            var uploadResult = await _uploadService.UploadProfileImage(file, userId, _env.WebRootPath, baseUrl);

            if (uploadResult.Status)
            {
                photoFromUserProfileDto.Url      = uploadResult.Url;
                photoFromUserProfileDto.PublicId = uploadResult.IsUplodedToLocal ? "1" : uploadResult.PublicId;

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

                //Delete image if it is in Cloudinary
                if (photoFromRepository?.PublicId != null && photoFromRepository?.PublicId != "0" && photoFromRepository?.PublicId != "1")
                {
                    var deletedResult = await _uploadService.DeleteFileFromCloudinary(photoFromRepository.PublicId);
                }
                //delete image if extention of oldImage and newImage is different
                //if extention of oldImage and newImage is same automatic oldImage Deleded
                if (photoFromRepository?.PublicId == "1" && uploadResult.IsUplodedToLocal && photoFromRepository.Url != photoFromUserProfileDto.Url)
                {
                    var deletedResult = _uploadService.DeleteFileFromLocal(photoFromRepository.Url.Split("/").Last(), _env.WebRootPath, "Files\\Images\\Profiles");
                }
                //delete oldimage if oldImage is in local and newImage in cloudinary
                if (photoFromRepository?.PublicId == "1" && !uploadResult.IsUplodedToLocal)
                {
                    var deletedResult = _uploadService.DeleteFileFromLocal(photoFromRepository.Url.Split("/").Last(), _env.WebRootPath, "Files\\Images\\Profiles");
                }

                _mapper.Map(photoFromUserProfileDto, photoFromRepository);

                _db.PhotoRepository.Update(photoFromRepository);

                if (await _db.SaveAsync())
                {
                    var photoForReturn = _mapper.Map <PhotoForReturnUserProfileDto>(photoFromRepository);
                    return(CreatedAtRoute("GetPhoto", routeValues: new { id = photoFromRepository.Id }, value: photoForReturn));
                }
                else
                {
                    return(BadRequest());
                }
            }
            else
            {
                return(BadRequest(uploadResult.Message));
            }
        }