public async Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } var formFiles = bindingContext.ActionContext?.HttpContext?.Request?.Form?.Files; if (formFiles == null || !formFiles.Any()) { return; } var list = new List <CustomFormFile>(); foreach (var formFile in formFiles) { using (var memoryStream = new MemoryStream()) { await formFile.CopyToAsync(memoryStream); var bytes = memoryStream.ToArray(); var fileBaseEncoded = Convert.ToBase64String(bytes); var item = new CustomFormFile(fileBaseEncoded, formFile.Name, formFile.Length, formFile.FileName); list.Add(item); } } bindingContext.Result = ModelBindingResult.Success(list.AsEnumerable()); }
public async Task Index_ShouldAddFileUploadToViewModel_WhenSupplied() { // Arrange var element = new ElementBuilder() .WithType(EElementType.FileUpload) .WithQuestionId("test") .Build(); var behaviour = new BehaviourBuilder() .WithBehaviourType(EBehaviourType.SubmitAndPay) .WithPageSlug("url") .Build(); var page = new PageBuilder() .WithElement(element) .WithPageSlug("page-one") .WithValidatedModel(true) .WithBehaviour(behaviour) .Build(); _pageService.Setup(_ => _.ProcessRequest(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Dictionary <string, dynamic> >(), It.IsAny <IEnumerable <CustomFormFile> >(), It.IsAny <bool>())) .ReturnsAsync(new ProcessRequestEntity { Page = page }); _pageService.Setup(_ => _.GetBehaviour(It.IsAny <ProcessRequestEntity>())).Returns(new Behaviour { BehaviourType = EBehaviourType.SubmitAndPay }); _paymentWorkflow.Setup(_ => _.Submit(It.IsAny <string>(), It.IsAny <string>())) .ReturnsAsync("https://www.return.url"); var collection = new List <CustomFormFile>(); var file = new CustomFormFile(String.Empty, "fileName", 0, "fileName"); collection.Add(file); var viewModel = new ViewModelBuilder() .WithEntry("Guid", Guid.NewGuid().ToString()) .Build(); // Act await _homeController.Index("form", "page-one", viewModel, collection); // Assert _pageService.Verify(service => service.ProcessRequest(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Dictionary <string, object> >(), collection, It.IsAny <bool>()), Times.AtLeastOnce); }