Beispiel #1
0
        private async Task <ImageDto> UploadImage(IFormFile file, bool isDefault, Guid?idImage = null)
        {
            Image img = new Image();

            if (idImage.HasValue)
            {
                img = await GetInner(idImage.Value);
            }
            else
            {
                img.Id        = Guid.NewGuid();
                img.IsDefault = isDefault;
            }
            var pathToSave = Path.Combine(_appSettings.Value.ImagePath, img.Id.ToString());

            Directory.CreateDirectory(pathToSave);

            var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
            var fullPath = Path.Combine(pathToSave, fileName);

            using (var stream = new FileStream(fullPath, FileMode.Create))
            {
                file.CopyTo(stream);
            }

            img.Path = fullPath;

            if (idImage.HasValue)
            {
                //immagine sovrascritta
                _dbCtx.Update(img);
            }
            else
            {
                //nuova immagine
                await _dbCtx.AddAsync(img);
            }

            await _dbCtx.SaveChangesAsync();

            return(img.ToDto());
        }