Ejemplo n.º 1
0
        public async Task <int> UploadBanner(int orderId, BannerToUpLoad bannerPhoto)
        {
            Banner banner;
            var    bannerCheckExist = await _db.Banners.FirstOrDefaultAsync(p => p.OrderId == orderId);

            if (bannerCheckExist == null)
            {
                if (bannerPhoto.File != null)
                {
                    //  2.

                    var uploadResult = new ImageUploadResult();                 //  3.

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

                            uploadResult = _cloudinary.Upload(uploadParams);    //  5.
                        }
                    }
                    bannerPhoto.Url      = uploadResult.Uri.ToString();            //  4. (cont'd)
                    bannerPhoto.PublicId = uploadResult.PublicId;
                    banner = new Banner
                    {
                        PhotoUrl    = bannerPhoto.Url,
                        OrderId     = orderId,
                        Description = bannerPhoto.Description,
                        DateAdded   = bannerPhoto.DateAdded,
                        PublicId    = bannerPhoto.PublicId
                    };
                    _db.Banners.Add(banner);
                    await _db.SaveChangesAsync();

                    return(1);
                }
                return(0);
            }
            return(-1);
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> CreateBanner(int orderId, BannerToUpLoad bannerPhoto)
        {
            try
            {
                var banner = await _bannerServices.UploadBanner(orderId, bannerPhoto);

                if (banner == 0)
                {
                    return(new BadRequestObjectResult(new { Message = "Thêm thất bại" }));
                }
                if (banner == -1)
                {
                    return(new BadRequestObjectResult(new { Message = "Banner ở vị trí này đã tồn tại, vui lòng thử lại" }));
                }
                return(Ok(new { Message = "Upload ảnh thành công" }));
            }
            catch (Exception ex)
            {
                return(new BadRequestObjectResult(new { Message = ex.Message.ToString() }));
            }
        }