Ejemplo n.º 1
0
        public async Task <IActionResult> UploadProductImages(IList <IFormFile> files, long productId)
        {
            if (files.Count == 0)
            {
                return(BadRequest());
            }

            IList <Image> images = new List <Image>();

            foreach (IFormFile file in files)
            {
                if (imageWriter.IsImageFile(file))
                {
                    //Create unique file name with UUID and file extension
                    string fileName       = Path.GetFileName(file.FileName);
                    string extension      = Path.GetExtension(fileName);
                    string uniqueFileName = Guid.NewGuid().ToString() + extension;

                    //Get file path in wwwroot folder
                    string imageUrl = "\\images\\products\\" + uniqueFileName;

                    //Get absolute path
                    string uploads = Path.Combine(_appHostingEnv.WebRootPath, "images", "products");
                    string path    = Path.Combine(uploads, uniqueFileName);

                    //Upload image on the server
                    await imageWriter.UploadImageAsync(file, path);

                    imageRepository.AddImage(new Image {
                        Name = uniqueFileName, Url = imageUrl, ProductID = productId
                    });
                    //Add new image in list to return back to client
                    Image image = new Image
                    {
                        Name = uniqueFileName,
                        Url  = imageUrl
                    };
                    images.Add(image);
                }
            }
            return(Ok(images));
        }