public async Task <IActionResult> AddPhotoForBlog(int blogId, PhotoBlogForCreation photoDto)
        {
            try
            {
                var result = await _photoService.AddPhotoForBlog(blogId, photoDto);

                if (result == 0)
                {
                    return(new BadRequestObjectResult(new { Message = "Không tìm thấy hình ảnh tải lên. Vui lòng kiểm tra lại!" }));
                }
                return(Ok(new { Message = "Đăng hình ảnh thành công!" }));
            }
            catch (Exception ex)
            {
                return(new BadRequestObjectResult(new { Message = ex.Message.ToString() }));
            }
        }
示例#2
0
        public async Task <int> AddPhotoForBlog(int blogId, PhotoBlogForCreation photoDto)
        {
            if (photoDto.File == null)
            {
                return(0);
            }
            PhotoBlog photo;
            var       blog = await _db                             //  1.
                             .Blogs
                             .Where(u => u.BlogId == blogId)
                             .FirstOrDefaultAsync();

            var uploadResult = new ImageUploadResult();


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

                    uploadResult = _cloudinary.Upload(uploadParams);    //  5.
                }
            }
            photoDto.Url      = uploadResult.Uri.ToString();            //  4. (cont'd)
            photoDto.PublicId = uploadResult.PublicId;
            photo             = new PhotoBlog
            {
                BlogId      = blogId,
                Url         = photoDto.Url,
                Description = photoDto.Description,
                DateAdded   = photoDto.DateAdded,
                PublicId    = photoDto.PublicId
            };
            blog.PhotoBlog = photo;
            await SaveAll();

            return(1);
        }