Exemplo n.º 1
0
        public async Task <ImageDto> UploadFileAsync(IFormFile file)
        {
            var extension = Path.GetExtension(file.FileName);

            if (string.IsNullOrEmpty(extension) || !_imageOptions.AllowedFileExtensions.Contains(extension))
            {
                throw new ImageStoreException($"'{extension}' extension is not allowed");
            }

            var fileName      = Guid.NewGuid().ToString();
            var thumbnailName = fileName + ".png";

            var filePath      = Path.Combine(_imageOptions.RootPath, _imageOptions.FilesPath, fileName);
            var thumbnailPath = Path.Combine(_imageOptions.RootPath, _imageOptions.ThumbnailsPath, thumbnailName);

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

            var thumbnailBytes = ParserService.ParseCaff(filePath);

            if (thumbnailBytes.Length == 0)
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }

                throw new ImageStoreException("Corrupted .caff file");
            }

            await File.WriteAllBytesAsync(thumbnailPath, thumbnailBytes);

            var image = new Dal.Entities.Image
            {
                FileName         = fileName,
                OriginalFileName = file.FileName,
                Uploader         = await _userManager.GetUserAsync(_user)
            };

            _dbContext.Images.Add(image);

            await _dbContext.SaveChangesAsync();

            return(new ImageDto
            {
                Id = image.Id,
                FileName = image.OriginalFileName,
                Url = $"/images/{image.FileName}",
                ThumbnailUrl = $"/thumbnails/{image.FileName}.png",
                Uploader = image.Uploader.UserName
            });
        }