public async Task <ResultResponse <DocumentDto> > AddDocumentAsync(DocumentCreateDto dto, int userId) { try { var uploader = await _usersRepository.GetAsync(userId); if (uploader == null) { return(ResultResponse <DocumentDto> .GetBadResponse(StatusCode.NotFound, "Не найден пользователь")); } byte[] bytes = new byte[dto.File.Length]; using (var stream = dto.File.OpenReadStream()) { await stream.ReadAsync(bytes, 0, (int)dto.File.Length); } var fileManager = new FileManager.Infrasructure.FileManager( baseAddress: _configurationService.WebAppSettings.BaseAddress, folder: _configurationService.UploadedFilesSettings.DocumentsFilesFolderRelativePath, progressLogger: _progressLogger); var uploadingResult = await fileManager.UploadFileAsync(new FileDto(dto.File.FileName, bytes), new string[] { "png", "jpg", "gif", "jpeg", "bmp" }); if (uploadingResult.IsSuccess) { var document = await _documentsRepository.AddAsync(new Document { length = (int)dto.File.Length, name = dto.Name, native_name = dto.File.FileName, path = uploadingResult.FilePath, created = DateTime.Now, creator_id = userId, }); if (document != null) { var documentView = await _documentViewsRepository.GetAsync(document.id); var documentDto = _mapper.Map <DocumentDto>(documentView); return(ResultResponse <DocumentDto> .GetSuccessResponse(documentDto)); } else { return(ResultResponse <DocumentDto> .GetInternalServerErrorResponse()); } } else { return(ResultResponse <DocumentDto> .GetInternalServerErrorResponse(uploadingResult.ErrorDescription)); } } catch (Exception ex) { _progressLogger.Error(ex, new { dto, userId }, GetType().Name, nameof(AddDocumentAsync)); return(ResultResponse <DocumentDto> .GetInternalServerErrorResponse()); } }
public async Task <ResultResponse <AdvertisementDto> > AddAdvertisementAsync(AdvertisementCreateDto dto, int creatorId) { try { int?imageId = null; // Идентификатор изображения (если прикреплеено) var creator = await _usersRepository.GetAsync(creatorId); if (creator == null) { return(ResultResponse <AdvertisementDto> .GetBadResponse(StatusCode.NotFound, "Пользователь не найден")); } if (dto.Image != null) // Загрузить картинку (опционально) { var fileManager = new FileManager.Infrasructure.FileManager( baseAddress: _configurationService.WebAppSettings.BaseAddress, folder: _configurationService.UploadedFilesSettings.AdvertisementFilesFolderRelativePath, progressLogger: _progressLogger); var bytes = new byte[dto.Image.Length]; using (var stream = dto.Image.OpenReadStream()) { await stream.ReadAsync(bytes, 0, bytes.Length); } var uploadingResult = await fileManager.UploadFileAsync( file : new FileDto(dto.Image.FileName, bytes), allowedFormats : new string[] { "png", "jpg", "gif", "jpeg", "bmp" }); if (uploadingResult.IsSuccess) // Если удалось загрузить изображение, то сохраняем в БД { var newAdvertisementFile = new AdvertisementFile { length = bytes.Length, native_name = dto.Image.FileName, path = uploadingResult.FilePath, uploaded = DateTime.Now, uploader_id = creatorId }; var addedFile = await _advertisementFilesRepository.AddAsync(newAdvertisementFile); if (addedFile == null) { return(ResultResponse <AdvertisementDto> .GetInternalServerErrorResponse("Не удалось загрузить изображение")); } else // Если загрузили изображение, то сохраняем его id { imageId = addedFile.id; } } else { return(ResultResponse <AdvertisementDto> .GetBadResponse(StatusCode.BadRequest, uploadingResult.ErrorDescription)); } } var advertisement = _mapper.Map <Advertisement>(dto); advertisement.created = DateTime.Now; advertisement.creator_id = creatorId; advertisement.image_file_id = imageId; var added = await _advertisementsRepository.AddAsync(advertisement); if (added == null) { return(ResultResponse <AdvertisementDto> .GetInternalServerErrorResponse("Произошла ошибка при добавлении объявления")); } else { var addedView = await _advertisementViewsRepository.GetAsync(added.id); var addedDto = _mapper.Map <AdvertisementDto>(addedView); return(ResultResponse <AdvertisementDto> .GetSuccessResponse(addedDto)); } } catch (Exception ex) { _progressLogger.Error(ex, new { dto, creatorId }, GetType().Name, nameof(AddAdvertisementAsync)); return(ResultResponse <AdvertisementDto> .GetInternalServerErrorResponse()); } }