コード例 #1
0
        public async Task <IActionResult> UploadMultipleImages(List <IFormFile> files, int?blogId)
        {
            if (files == null || blogId == null)
            {
                return(BadRequest());
            }

            var blog = await _blogService.GetByIdWithImages((int)blogId);

            if (blog.Success)
            {
                var dir = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/img/uploads");

                foreach (var item in files)
                {
                    var filePath = Path.Combine(dir, item.FileName);
                    var imageUrl = Path.Combine(Path.DirectorySeparatorChar.ToString(), "img", "uploads", item.FileName);
                    if (blog.Data.BlogImages.Find(i => i.ImageUrl == imageUrl) != null)
                    {
                        return(BadRequest($"{item.FileName} adında bir dosya daha bulundu. Lütfen ismini değiştiriniz."));
                    }

                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await item.CopyToAsync(stream);

                        blog.Data.BlogImages.Add(new BlogImage {
                            BlogId = (int)blogId, ImageUrl = imageUrl
                        });
                    }
                }

                var result = await _blogService.AddImages(blog.Data);

                return(Ok());
            }

            return(BadRequest("Resimler yüklenemedi."));
        }