Exemplo n.º 1
0
        public async Task <string> CreateFromBase64(
            FilesTypes fileType,
            Guid entityId,
            Guid creatorId,
            SrbacRoles creatorRole,
            string contentBase64 = null,
            string fileName      = null
            )
        {
            try
            {
                if (string.IsNullOrWhiteSpace(contentBase64))
                {
                    return(null);
                }

                if (string.IsNullOrWhiteSpace(fileName))
                {
                    fileName = Guid.NewGuid().ToString();
                }

                var name      = Path.GetFileNameWithoutExtension(fileName);
                var extension = GetFileExtension(contentBase64);

                using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
                var fileModel = await _fileRepository.Create(new FileModel
                {
                    EntityType = fileType,
                    Extension  = extension,
                    Name       = name,
                    EntityId   = entityId, CreatorId = creatorId
                });

                var path = Path.Combine(
                    _fileStorageConfiguration.AbsolutePath,
                    fileType.ToString(),
                    entityId.ToString()
                    );
                Directory.CreateDirectory(path);

                var filePath = Path.Combine(path, $"{fileModel.Id.ToString()}.{extension}");
                await File.WriteAllBytesAsync(filePath, Convert.FromBase64String(contentBase64));

                await _auditService.Success(
                    AuditOperationTypes.CreateFile,
                    "",
                    fileModel,
                    fileModel.Id,
                    creatorId,
                    creatorRole
                    );

                scope.Complete();
                return(await GetFileUrl(entityId, fileType));
            }
            catch (Exception e)
            {
                await _auditService.Error(
                    AuditOperationTypes.CreateFile,
                    e.Message,
                    new AuditErrorObjectContainer
                {
                    Model = new FileModel
                    {
                        EntityType = fileType,
                        Name       = fileName,
                        EntityId   = entityId
                    },
                    Error = e
                },
                    null,
                    creatorId,
                    creatorRole
                    );

                throw;
            }
        }