Пример #1
1
        public async Task FormFileModelBinder_ReturnsNoResult_WithEmptyContentDisposition()
        {
            // Arrange
            var formFiles = new FormFileCollection();
            formFiles.Add(new Mock<IFormFile>().Object);
            var httpContext = GetMockHttpContext(GetMockFormCollection(formFiles));
            var bindingContext = GetBindingContext(typeof(IFormFile), httpContext);
            var binder = new FormFileModelBinder();

            // Act
            var result = await binder.BindModelAsync(bindingContext);

            // Assert
            Assert.NotEqual(ModelBindingResult.NoResult, result);
            Assert.Null(result.Model);
        }
Пример #2
0
        public async Task <bool> AddOrderPic([FromForm] IFormCollection formCollection)
        {
            bool result = false;

            FormFileCollection filelist = (FormFileCollection)formCollection.Files;

            foreach (IFormFile file in filelist)
            {
                string uploadPath = _hostingEnvironment.WebRootPath + $@"\Files\Pictures\";
                string FileName   = file.FileName;

                DirectoryInfo di = new DirectoryInfo(uploadPath);


                if (!di.Exists)
                {
                    di.Create();
                }

                using (FileStream fs = System.IO.File.Create(uploadPath + FileName))
                {
                    // 复制文件
                    file.CopyTo(fs);
                    // 清空缓冲区数据
                    fs.Flush();
                }
                result = true;
            }
            return(result);
        }
Пример #3
0
        public async Task AddGameSuccesAsync()
        {
            //arrange
            var environment = new Mock <IWebHostEnvironment>();
            var controller  = new GameController(_games.Object, environment.Object);
            var testGame    = new Game {
                Id = 1, Name = "Outlast", Quantity = 5, Category = "Horror", Platform = "PC"
            };
            // mock http context class and file upload method
            IFormFileCollection formCollection = new FormFileCollection();


            _mockHttpContext.Setup(s => s.Request.Form.Files).Returns(formCollection);
            controller.ControllerContext.HttpContext = _mockHttpContext.Object;
            //act
            var result = controller.AddGame(testGame);

            // asssert
            Assert.That(result, Is.TypeOf(typeof(Task <IActionResult>)));
            var resultView = (RedirectToActionResult)result.Result;

            Assert.AreEqual("Index", resultView.ActionName);
            Assert.AreEqual(1, _gameList.Count); // verify that game has been added
            Assert.AreEqual("Outlast", _gameList.Find(u => u.Id == testGame.Id).Name);
        }
        public void WithFormShouldWorkCorrectly()
        {
            var stream = new MemoryStream();
            var files  = new FormFileCollection
            {
                new FormFile(stream, 0, 0, "FirstFile", "FirstFileName"),
                new FormFile(stream, 0, 0, "SecondFile", "SecondFileName"),
            };

            MyMvc
            .Controller <MvcController>()
            .WithHttpRequest(request => request
                             .WithForm(new FormCollection(
                                           new Dictionary <string, StringValues>
            {
                ["Field"]        = new StringValues("FieldValue"),
                ["AnotherField"] = new StringValues(new[] { "AnotherFieldValue", "SecondFieldValue" }),
            },
                                           files)))
            .ShouldPassFor()
            .TheHttpRequest(builtRequest =>
            {
                Assert.Equal(2, builtRequest.Form.Count);
                Assert.Equal("FieldValue", builtRequest.Form["Field"]);
                Assert.Equal("AnotherFieldValue,SecondFieldValue", builtRequest.Form["AnotherField"]);
                Assert.Equal(2, builtRequest.Form.Files.Count);
                Assert.Same(files[0], builtRequest.Form.Files[0]);
                Assert.Same(files[1], builtRequest.Form.Files[1]);
            });
        }
Пример #5
0
        public IActionResult validateExcel([FromForm] IFormCollection formCollection, string orgCode, string orgName, DateTime dateMonth)
        {
            Dictionary <string, object> r = new Dictionary <string, object>();

            try
            {
                FormFileCollection fileCollection = (FormFileCollection)formCollection.Files;
                foreach (var file in fileCollection)
                {
                    StreamReader reader    = new StreamReader(file.OpenReadStream());
                    String       Content   = reader.ReadToEnd();
                    String       name      = file.FileName;
                    String       timestamp = string.Format("{0:yyyyMMddHHmmssffff}", dateMonth) + "_" + orgCode;
                    String       filePath  = Directory.GetCurrentDirectory() + "\\Files\\taxdetail\\" + timestamp + "_" + name;
                    if (System.IO.File.Exists(filePath))
                    {
                        System.IO.File.Delete(filePath);
                    }
                    using (FileStream fs = System.IO.File.Create(filePath))
                    {
                        file.CopyTo(fs);
                        fs.Flush();
                    }
                    r = TM.validateExcel(filePath, orgCode, orgName, dateMonth);
                }
            }
            catch (Exception e)
            {
                r["code"]    = -1;
                r["message"] = "导入失败!" + e.Message;
            }
            return(Json(r));
        }
    /// <inheritdoc />
    ///  <summary>
    ///  It Binds IFormFile to Common file, getting the file
    ///  from the binding context
    ///  </summary>
    ///  <param name="bindingContext">Http Context</param>
    ///  <returns>Completed Task</returns>
    // TODO: Bind this context to ICommonFile or ICommonFileCollection object
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        dynamic model;

        if (bindingContext == null)
        {
            throw new ArgumentNullException(nameof(bindingContext));
        }
        var formFiles = bindingContext.ActionContext.HttpContext.Request.Form.Files;

        if (!formFiles.Any())
        {
            return(Task.CompletedTask);
        }
        if (formFiles.Count > 1)
        {
            model = formFiles.AsParallel().Select(_expression);
        }
        else
        {
            model = new FormFileCollection();
            model.AddRange(filteredFiles.AsParallel().Select(_expression));
        }
        bindingContext.Result = ModelBindingResult.Success(model);
        return(Task.CompletedTask);
    }
Пример #7
0
        public static string GetNiftiFileErrorMsg(IFormCollection formCollection)
        {
            if (formCollection == null)
            {
                return("Form is empty");
            }
            FormFileCollection fileCollection = (FormFileCollection)formCollection.Files;

            if (fileCollection == null || fileCollection.Count != 1)
            {
                return("file count error:" + fileCollection.Count);
            }
            long size = 0;

            foreach (FormFile file in fileCollection)
            {
                string   name       = file.FileName;
                string[] extentions = name.Split(".");
                if (extentions[extentions.Length - 1].ToLower() != "nii")
                {
                    return("wrong type:" + file.ContentType);
                }
                size += file.Length;
                if (size > AppSettingUtility.MaxNIFTISize)
                {
                    return("the size of files exceed " + AppSettingUtility.MaxNIFTISize / (1024 * 1024) + "MB");
                }
            }
            return(null);
        }
Пример #8
0
        public static string GetImageFileErrorMsg(IFormCollection formCollection)
        {
            if (formCollection == null)
            {
                return("Form is empty");
            }
            FormFileCollection fileCollection = (FormFileCollection)formCollection.Files;

            if (fileCollection == null || fileCollection.Count != 1)
            {
                return("file count error:" + fileCollection.Count);
            }
            long size = 0;

            foreach (FormFile file in fileCollection)
            {
                string   name        = file.FileName;
                string[] contentType = file.ContentType.Split("/");
                if (contentType.Length <= 1)
                {
                    return("wrong Content-Type:" + file.ContentType);
                }
                else if (contentType[0] != "image" || Array.IndexOf(imageFileTypes.Split(","), contentType[1]) == -1)
                {
                    return("wrong type:" + file.ContentType + ",file type needs to be" + imageFileTypes);
                }
                size += file.Length;
                if (size > AppSettingUtility.MaxImageSize)
                {
                    return("the size of files exceed " + AppSettingUtility.MaxImageSize / (1024 * 1024) + "MB");
                }
            }
            return(null);
        }
Пример #9
0
        public static string GetVideoFileErrorMsg(IFormCollection formCollection)
        {
            if (formCollection == null)
            {
                return("Form is empty");
            }
            FormFileCollection fileCollection = (FormFileCollection)formCollection.Files;

            if (fileCollection == null || fileCollection.Count != 1)
            {
                return("file count error:" + fileCollection.Count);
            }
            long size = 0;

            foreach (FormFile file in fileCollection)
            {
                string name = file.FileName;
                if (file.ContentType == "video/mpeg4")
                {
                    return("wrong type:" + file.ContentType);
                }
                size += file.Length;
                if (size > AppSettingUtility.MaxVideoSize)
                {
                    return("the size of files exceed " + AppSettingUtility.MaxVideoSize / (1024 * 1024) + "MB");
                }
            }
            return(null);
        }
Пример #10
0
        public string Post([FromForm] IFormCollection formCollection)
        {
            string result          = "";
            string webRootPath     = _hostingEnvironment.WebRootPath;
            string contentRootPath = _hostingEnvironment.ContentRootPath;

            FormFileCollection filelist = (FormFileCollection)formCollection.Files;

            foreach (IFormFile file in filelist)
            {
                String Tpath    = "/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
                string name     = file.FileName;
                string FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                string FilePath = webRootPath + Tpath;

                string        type = System.IO.Path.GetExtension(name);
                DirectoryInfo di   = new DirectoryInfo(FilePath);


                if (!di.Exists)
                {
                    di.Create();
                }

                using (FileStream fs = System.IO.File.Create(FilePath + FileName + type))
                {
                    // 复制文件
                    file.CopyTo(fs);
                    // 清空缓冲区数据
                    fs.Flush();
                }
                result = "1";
            }
            return(result);
        }
        public async Task Then_validation_passes()
        {
            var files    = new FormFileCollection();
            var response = await Handler.Handle(new SubmitPageOfFilesRequest(ApplicationId, SectionId, "1", files), CancellationToken.None);

            response.Value.ValidationPassed.Should().BeTrue();
        }
        public async Task <IActionResult> UploadAppealFile([FromForm] UploadAppealFileRequest request)
        {
            if (request.AppealFile is null)
            {
                return(BadRequest());
            }

            var fileCollection = new FormFileCollection {
                request.AppealFile
            };
            var uploadedSuccessfully = await _fileStorageService.UploadApplicationFiles(request.ApplicationId, fileCollection, ContainerType.Appeals, new CancellationToken());

            if (!uploadedSuccessfully)
            {
                _logger.LogError($"Unable to upload appeal file for application: {request.ApplicationId}");
                return(BadRequest());
            }

            var command = new UploadAppealFileCommand
            {
                ApplicationId = request.ApplicationId,
                AppealFile    = await request.AppealFile.ToFileUpload(),
                UserId        = request.UserId,
                UserName      = request.UserName
            };

            await _mediator.Send(command);

            return(new OkResult());
        }
        public String PostFile([FromForm] IFormCollection formCollection)
        {
            String result = "Fail";

            if (formCollection.ContainsKey("user"))
            {
                var user = formCollection["user"];
            }
            FormFileCollection fileCollection = (FormFileCollection)formCollection.Files;

            foreach (IFormFile file in fileCollection)
            {
                StreamReader reader   = new StreamReader(file.OpenReadStream());
                String       content  = reader.ReadToEnd();
                String       name     = file.FileName;
                String       filename = @"D:/Test/" + name;
                if (System.IO.File.Exists(filename))
                {
                    System.IO.File.Delete(filename);
                }
                using (FileStream fs = System.IO.File.Create(filename))
                {
                    // 复制文件
                    file.CopyTo(fs);
                    // 清空缓冲区数据
                    fs.Flush();
                }
                result = "Success";
            }
            return(result);
        }
Пример #14
0
        /// <summary>
        /// 同步方法上传文件
        /// </summary>
        /// <param name="formCollection">控制器接收格式</param>
        /// <param name="SavePath">保存地址</param>
        /// <returns></returns>
        public static JArray UploadFile(IFormCollection formCollection, string SavePath)
        {
            FormFileCollection fileCollection = (FormFileCollection)formCollection.Files;
            string             BasePath       = Directory.GetCurrentDirectory();
            JArray             arr            = new JArray();

            foreach (var file in fileCollection)
            {
                JObject obj = new JObject();
                //获取文件格式名称
                string FileFormat = Path.GetExtension(file.FileName);
                string name       = Path.GetFileNameWithoutExtension(file.FileName) + DateTime.Now.ToString("yyyyMMddHHmmss");
                while (File.Exists($"{BasePath}{SavePath}{name}{FileFormat}"))
                {
                    name = file.Name + DateTime.Now.ToString("yyyyMMddHHmmss");
                }
                using (FileStream fs = File.Create($"{BasePath}{SavePath}{name}{FileFormat}"))
                {
                    file.CopyTo(fs);
                }
                obj.Add("ID", Guid.NewGuid());
                obj.Add("FILE_NAME", file.FileName);
                obj.Add("FILE_URL", $"{name}{FileFormat}");
                arr.Add(obj);
            }
            return(arr);
        }
Пример #15
0
        public IActionResult CalculateImportSalary([FromForm] IFormCollection formCollection, string userId, string importModel, string taxOffice)
        {
            Dictionary <string, object> r = new Dictionary <string, object>();

            try
            {
                FormFileCollection fileCollection = (FormFileCollection)formCollection.Files;
                foreach (IFormFile file in fileCollection)
                {
                    StreamReader reader    = new StreamReader(file.OpenReadStream());
                    String       content   = reader.ReadToEnd();
                    String       name      = file.FileName;
                    String       timestamp = DateTime.Now.ToString("yyyy-MM-dd") + Guid.NewGuid().ToString();
                    String       filePath  = System.IO.Directory.GetCurrentDirectory() + "\\Files\\salary\\" + timestamp + "_" + name;
                    if (System.IO.File.Exists(filePath))
                    {
                        System.IO.File.Delete(filePath);
                    }
                    using (FileStream fs = System.IO.File.Create(filePath))
                    {
                        // 复制文件
                        file.CopyTo(fs);
                        // 清空缓冲区数据
                        fs.Flush();
                    }
                    r = md.ImportTaxSalary(filePath, userId, importModel, taxOffice);
                }
            }
            catch (Exception ex)
            {
                r["code"]    = -1;
                r["message"] = "导入失败!" + ex.Message;
            }
            return(Json(r));
        }
        public void Validate_should_be_invalid_if_more_than_max_size()
        {
            const string questionId   = "QId";
            const string errorMessage = "The file is larger than 1 Mb";

            var config = new CustomValidationConfiguration
            {
                Name         = "FileSizeMaxMb",
                QuestionId   = "QId",
                Value        = "1",
                ErrorMessage = errorMessage
            };

            var files = new FormFileCollection();

            files.Add(CreateFile("This file should be ignored", 5000000));
            files.Add(CreateFile("QId", 1024 * 1024 + 1));

            var validator = new FileSizeMaxMbValidator(config, files);

            var result = validator.Validate();

            result.IsValid.Should().BeFalse();
            result.QuestionId.Should().Be(questionId);
            result.ErrorMessage.Should().Be(errorMessage);
        }
        public static ControllerContext Setup(string buttonToAdd)
        {
            var user = MockedUser.Setup();

            var controllerContext = new ControllerContext()
            {
                HttpContext = new DefaultHttpContext()
                {
                    User = user
                }
            };

            if (!string.IsNullOrEmpty(buttonToAdd))
            {
                var clarificationFileName = "file.pdf";
                var file = new FormFile(new MemoryStream(), 0, 0, clarificationFileName, clarificationFileName);
                var formFileCollection = new FormFileCollection {
                    file
                };
                var dictionary = new Dictionary <string, StringValues>();
                dictionary.Add(buttonToAdd, clarificationFileName);
                controllerContext.HttpContext.Request.Form = new FormCollection(dictionary, formFileCollection);
            }
            else
            {
                controllerContext.HttpContext.Request.Form = new FormCollection(new Dictionary <string, StringValues>());
            }

            return(controllerContext);
        }
        public async Task UploadStudentWithoutId_Returns_StudentWithGuidEmptyId()
        {
            var multipartFormDataFormatter = new MultipartFormDataFormatter();
            var formFileCollection         = new FormFileCollection();

            var models = new Dictionary <string, StringValues>();

            var formCollection  = new FormCollection(models, formFileCollection);
            var httpContextMock = new Mock <HttpContext>();
            var httpRequestMock = new Mock <HttpRequest>();

            httpRequestMock.Setup(x => x.Form)
            .Returns(formCollection);

            httpRequestMock.Setup(x => x.ReadFormAsync(It.IsAny <CancellationToken>()))
            .ReturnsAsync(formCollection);

            httpContextMock.SetupGet(x => x.Request)
            .Returns(httpRequestMock.Object);

            var inputFormatter = new InputFormatterContext(httpContextMock.Object, string.Empty,
                                                           new ModelStateDictionary(), new EmptyModelMetaData(ModelMetadataIdentity.ForType(typeof(StudentViewModel))),
                                                           (stream, encoding) => TextReader.Null);

            var handledResult = await multipartFormDataFormatter
                                .ReadRequestBodyAsync(inputFormatter);

            Assert.IsInstanceOf <InputFormatterResult>(handledResult);

            var student = handledResult.Model as StudentViewModel;

            Assert.NotNull(student);
            Assert.AreEqual(Guid.Empty, student.Id);
        }
Пример #19
0
        public IActionResult validateTaxBonus([FromForm] IFormCollection formCollection, string orgCode, DateTime dateMonth)
        {
            Dictionary <string, object> r = new Dictionary <string, object>();

            try
            {
                FormFileCollection fileCollection = (FormFileCollection)formCollection.Files;
                foreach (IFormFile file in fileCollection)
                {
                    StreamReader reader    = new StreamReader(file.OpenReadStream());
                    String       content   = reader.ReadToEnd();
                    String       name      = file.FileName;
                    String       timestamp = string.Format("{0:yyyyMMdd}", dateMonth) + "_" + orgCode;
                    String       filePath  = System.IO.Directory.GetCurrentDirectory() + "\\Files\\onebonus\\" + timestamp + "_" + name;
                    if (System.IO.File.Exists(filePath))
                    {
                        System.IO.File.Delete(filePath);
                    }
                    using (FileStream fs = System.IO.File.Create(filePath))
                    {
                        // 复制文件
                        file.CopyTo(fs);
                        // 清空缓冲区数据
                        fs.Flush();
                    }
                    r = tobm.ValidateTaxBonus(filePath, orgCode, dateMonth);
                }
            }
            catch (Exception ex)
            {
                r["code"]    = -1;
                r["message"] = "导入失败!" + ex.Message;
            }
            return(Json(r));
        }
        private static ActionContext ContextWithEmptyCsvFile()
        {
            var formFile = new FormFile(Stream.Null, long.MinValue, 0, "TestFile.csv", "TestFile.csv")
            {
                Headers     = new HeaderDictionary(),
                ContentType = "text/csv"
            };
            var formFileCollection = new FormFileCollection {
                formFile
            };

            var request = Substitute.For <HttpRequest>();

            request.Form = new FormCollection(new Dictionary <string, StringValues>(), formFileCollection);
            request.GetMultipartBoundary().Returns("requestTest");

            var httpContext = Substitute.For <HttpContext>();

            var actionContext = Substitute.For <ActionContext>();

            actionContext.HttpContext = httpContext;
            actionContext.HttpContext.Request.Returns(request);

            actionContext.RouteData        = new RouteData();
            actionContext.ActionDescriptor = new ControllerActionDescriptor();

            return(actionContext);
        }
Пример #21
0
        private static IFormCollection GetMockFormCollection(FormFileCollection formFiles)
        {
            var formCollection = new Mock <IFormCollection>();

            formCollection.Setup(f => f.Files).Returns(formFiles);
            return(formCollection.Object);
        }
Пример #22
0
        public async Task FormFileModelBinder_UsesFieldNameForTopLevelObject(bool isTopLevel, string expected)
        {
            // Arrange
            var formFiles = new FormFileCollection();

            formFiles.Add(GetMockFormFile("FieldName", "file1.txt"));
            formFiles.Add(GetMockFormFile("ModelName", "file1.txt"));
            var httpContext = GetMockHttpContext(GetMockFormCollection(formFiles));

            var bindingContext = GetBindingContext(typeof(IFormFile), httpContext);

            bindingContext.IsTopLevelObject = isTopLevel;
            bindingContext.FieldName        = "FieldName";
            bindingContext.ModelName        = "ModelName";

            var binder = new FormFileModelBinder();

            // Act
            var result = await binder.BindModelAsync(bindingContext);

            // Assert
            Assert.NotEqual(ModelBindingResult.NoResult, result);
            Assert.True(result.IsModelSet);
            var file = Assert.IsAssignableFrom <IFormFile>(result.Model);

            ContentDispositionHeaderValue contentDisposition;

            ContentDispositionHeaderValue.TryParse(file.ContentDisposition, out contentDisposition);
            Assert.Equal(expected, contentDisposition.Name);
        }
Пример #23
0
        public JsonResult PostFile([FromForm] IFormCollection formCollection)
        {
            string             result         = "fail";
            FormFileCollection fileCollection = (FormFileCollection)formCollection.Files;

            foreach (IFormFile file in fileCollection)
            {
                StreamReader reader  = new StreamReader(file.OpenReadStream());
                String       content = reader.ReadToEnd();

                String name     = file.FileName;
                string ext      = Path.GetExtension(name);
                String filename = DateTime.Now.ToString("yyyyMMddhhmmss") + Guid.NewGuid() + ext;
                string allPath  = this.uploadDir + filename;
                using (FileStream fs = System.IO.File.Create(allPath))
                {
                    // 复制文件
                    file.CopyTo(fs);
                    // 清空缓冲区数据
                    fs.Flush();
                }
                result = filename;
            }
            dynamic dyObj = new { ret = result };

            return(new JsonResult(dyObj));
        }
Пример #24
0
        public string Post([FromForm] IFormCollection formCollection)
        {
            var getCookie = "";

            HttpContext.Request.Cookies.TryGetValue("getCookie", out getCookie);
            string             result          = "";
            string             webRootPath     = "C://文稿";
            string             contentRootPath = _hostingEnvironment.ContentRootPath;
            String             Tpath           = "/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
            string             FilePath        = webRootPath + Tpath;
            FormFileCollection filelist        = (FormFileCollection)formCollection.Files;

            foreach (IFormFile file in filelist)
            {
                string        name     = file.FileName;
                string        FileName = file.FileName;
                string        type     = System.IO.Path.GetExtension(name);
                DirectoryInfo di       = new DirectoryInfo(FilePath);
                if (!di.Exists)
                {
                    di.Create();
                }
                using (FileStream fs = System.IO.File.Create(FilePath + FileName))
                {
                    // 复制文件
                    file.CopyTo(fs);
                    // 清空缓冲区数据
                    fs.Flush();
                    FileService.upload(FilePath, FileName, "胡佳俊", "无");
                }
                result = "0";
            }
            return("{\"msg\":" + "\"\"," + "\"code\":" + result + "}");
        }
Пример #25
0
        public async Task FormFileModelBinder_ExpectMultipleFiles_BindSuccessful()
        {
            // Arrange
            var formFiles = new FormFileCollection();
            formFiles.Add(GetMockFormFile("file", "file1.txt"));
            formFiles.Add(GetMockFormFile("file", "file2.txt"));
            var httpContext = GetMockHttpContext(GetMockFormCollection(formFiles));
            var bindingContext = GetBindingContext(typeof(IEnumerable<IFormFile>), httpContext);
            var binder = new FormFileModelBinder();

            // Act
            var result = await binder.BindModelAsync(bindingContext);

            // Assert
            Assert.NotEqual(ModelBindingResult.NoResult, result);
            Assert.True(result.IsModelSet);

            var entry = bindingContext.ValidationState[result.Model];
            Assert.True(entry.SuppressValidation);
            Assert.Null(entry.Key);
            Assert.Null(entry.Metadata);

            var files = Assert.IsAssignableFrom<IList<IFormFile>>(result.Model);
            Assert.Equal(2, files.Count);
        }
Пример #26
0
        [Consumes("multipart/form-data")]//此处为新增

        public IActionResult UploadExcelFiles([FromForm] IFormCollection formCollection)
        {
            Dictionary <string, object> r = new Dictionary <string, object>();

            try
            {
                FormFileCollection  fileCollection = (FormFileCollection)formCollection.Files;
                IFormFileCollection dd             = Request.Form.Files;
                IFormFile           file           = fileCollection[0];
                string path = file.FileName;
                //HttpFileCollection
                Stream     aa       = file.OpenReadStream();
                Stream     BB       = dd[0].OpenReadStream();
                string     modePath = System.IO.Directory.GetCurrentDirectory() + "\\ExcelModel\\组织结构模板.xlsx";//原始文件
                string     mes      = "";
                DataTable  dt       = new DataTable();
                ExcelTools tool     = new ExcelTools();
                tool.GetDataTable(aa, path, modePath, ref mes, ref dt);
                return(Json(r));
            }
            catch (Exception ex)
            {
                r["code"]    = -1;
                r["message"] = ex.Message;
            }
            return(Json(r));
        }
        public void Validate_should_be_valid_if_less_than_or_equal_to_max_size(long fileSizeBytes)
        {
            const string questionId = "QId";

            var config = new CustomValidationConfiguration
            {
                Name         = "FileSizeMaxMb",
                QuestionId   = questionId,
                Value        = "1",
                ErrorMessage = "The file is larger than 1 Mb"
            };

            var files = new FormFileCollection();

            files.Add(CreateFile("This file should be ignored", 5000000));
            files.Add(CreateFile("QId", fileSizeBytes));

            var validator = new FileSizeMaxMbValidator(config, files);

            var result = validator.Validate();

            result.IsValid.Should().BeTrue();
            result.QuestionId.Should().Be(questionId);
            result.ErrorMessage.Should().BeNull();
        }
Пример #28
0
        public async Task FormFileModelBinder_ExpectMultipleFiles_BindSuccessful()
        {
            // Arrange
            var formFiles = new FormFileCollection();

            formFiles.Add(GetMockFormFile("file", "file1.txt"));
            formFiles.Add(GetMockFormFile("file", "file2.txt"));
            var httpContext    = GetMockHttpContext(GetMockFormCollection(formFiles));
            var bindingContext = GetBindingContext(typeof(IEnumerable <IFormFile>), httpContext);
            var binder         = new FormFileModelBinder();

            // Act
            var result = await binder.BindModelAsync(bindingContext);

            // Assert
            Assert.NotEqual(ModelBindingResult.NoResult, result);
            Assert.True(result.IsModelSet);

            var entry = bindingContext.ValidationState[result.Model];

            Assert.True(entry.SuppressValidation);
            Assert.Null(entry.Key);
            Assert.Null(entry.Metadata);

            var files = Assert.IsAssignableFrom <IList <IFormFile> >(result.Model);

            Assert.Equal(2, files.Count);
        }
Пример #29
0
        public async Task UploadClarificationFile_with_file_calls_file_upload_which_fails_returns_bad_request()
        {
            var clarificationFileName = "file.pdf";
            var file = new FormFile(new MemoryStream(), 0, 0, clarificationFileName, clarificationFileName);
            var formFileCollection = new FormFileCollection {
                file
            };

            _controller.HttpContext.Request.Form = new FormCollection(new Dictionary <string, StringValues>(), formFileCollection);

            var command = new SubcontractorDeclarationClarificationFileCommand
            {
                UserId   = "user id",
                UserName = "******"
            };

            _fileStorage.Setup(x => x.UploadFiles(_applicationId, RoatpWorkflowSequenceIds.YourOrganisation,
                                                  RoatpWorkflowSectionIds.YourOrganisation.ExperienceAndAccreditations,
                                                  RoatpClarificationUpload.SubcontractorDeclarationClarificationFile, formFileCollection,
                                                  ContainerType.Gateway, It.IsAny <CancellationToken>())).ReturnsAsync(false);

            var result = await _controller.UploadClarificationFile(_applicationId, command);

            var expectedResult = new BadRequestResult();

            Assert.AreEqual(expectedResult.ToString(), result.ToString());
            _mediator.Verify(x => x.Send(It.IsAny <AddSubcontractorDeclarationFileUploadRequest>(), It.IsAny <CancellationToken>()), Times.Never);
        }
Пример #30
0
        public async Task FormFileModelBinder_UsesFieldNameForTopLevelObject(bool isTopLevel, string expected)
        {
            // Arrange
            var formFiles = new FormFileCollection
            {
                GetMockFormFile("FieldName", "file1.txt"),
                GetMockFormFile("ModelName", "file1.txt")
            };
            var httpContext = GetMockHttpContext(GetMockFormCollection(formFiles));

            var bindingContext = GetBindingContext(typeof(IFormFile), httpContext);

            bindingContext.IsTopLevelObject = isTopLevel;
            bindingContext.FieldName        = "FieldName";
            bindingContext.ModelName        = "ModelName";

            var binder = new FormFileModelBinder(NullLoggerFactory.Instance);

            // Act
            await binder.BindModelAsync(bindingContext);

            // Assert
            Assert.True(bindingContext.Result.IsModelSet);
            var file = Assert.IsAssignableFrom <IFormFile>(bindingContext.Result.Model);

            Assert.Equal(expected, file.Name);
        }
Пример #31
0
        public void GetFilesByName()
        {
            var f1 = new FormFile
            {
                Name = "a"
            };
            var f2 = new FormFile
            {
                Name = "b"
            };
            var f3 = new FormFile
            {
                Name = "a"
            };
            var x = new FormFileCollection
            {
                InnerList = new List <FormFile>
                {
                    f1, f2, f3
                }
            };
            var found = x.GetFiles("a");

            Assert.Equal(2, found.Count);
            Assert.Same(f1, found[0]);
            Assert.Same(f3, found[1]);
        }
Пример #32
0
        public void EnumrableInterface()
        {
            var x = new FormFileCollection();
            var y = (IEnumerable <IFormFile>)x;

            using var enumerator = y.GetEnumerator();
            Assert.False(enumerator.MoveNext());
        }
        public async Task FormFileModelBinder_ReturnsNull_WhenNoFilePosted()
        {
            // Arrange
            var formFiles = new FormFileCollection();
            var httpContext = GetMockHttpContext(GetMockFormCollection(formFiles));
            var bindingContext = GetBindingContext(typeof(IFormFile), httpContext);
            var binder = new FormFileModelBinder();

            // Act
            var result = await binder.BindModelAsync(bindingContext);

            // Assert
            Assert.NotNull(result);
            Assert.Null(result.Model);
        }
Пример #34
0
        public async Task FormFileModelBinder_FilesWithQuotedContentDisposition_BindSuccessful()
        {
            // Arrange
            var formFiles = new FormFileCollection();
            formFiles.Add(GetMockFormFileWithQuotedContentDisposition("file", "file1.txt"));
            formFiles.Add(GetMockFormFileWithQuotedContentDisposition("file", "file2.txt"));
            var httpContext = GetMockHttpContext(GetMockFormCollection(formFiles));
            var bindingContext = GetBindingContext(typeof(IEnumerable<IFormFile>), httpContext);
            var binder = new FormFileModelBinder();

            // Act
            var result = await binder.BindModelAsync(bindingContext);

            // Assert
            Assert.NotEqual(ModelBindingResult.NoResult, result);
            var files = Assert.IsAssignableFrom<IList<IFormFile>>(result.Model);
            Assert.Equal(2, files.Count);
        }
Пример #35
0
        public async Task FormFileModelBinder_ExpectSingleFile_BindFirstFile()
        {
            // Arrange
            var formFiles = new FormFileCollection();
            formFiles.Add(GetMockFormFile("file", "file1.txt"));
            formFiles.Add(GetMockFormFile("file", "file2.txt"));
            var httpContext = GetMockHttpContext(GetMockFormCollection(formFiles));
            var bindingContext = GetBindingContext(typeof(IFormFile), httpContext);
            var binder = new FormFileModelBinder();

            // Act
            var result = await binder.BindModelAsync(bindingContext);

            // Assert
            Assert.NotNull(result);
            var file = Assert.IsAssignableFrom<IFormFile>(result.Model);
            Assert.Equal("form-data; name=file; filename=file1.txt",
                         file.ContentDisposition);
        }
Пример #36
0
        public async Task FormFileModelBinder_UsesFieldNameForTopLevelObject(bool isTopLevel, string expected)
        {
            // Arrange
            var formFiles = new FormFileCollection();
            formFiles.Add(GetMockFormFile("FieldName", "file1.txt"));
            formFiles.Add(GetMockFormFile("ModelName", "file1.txt"));
            var httpContext = GetMockHttpContext(GetMockFormCollection(formFiles));

            var bindingContext = GetBindingContext(typeof(IFormFile), httpContext);
            bindingContext.IsTopLevelObject = isTopLevel;
            bindingContext.FieldName = "FieldName";
            bindingContext.ModelName = "ModelName";

            var binder = new FormFileModelBinder();

            // Act
            var result = await binder.BindModelAsync(bindingContext);

            // Assert
            Assert.NotEqual(ModelBindingResult.NoResult, result);
            Assert.True(result.IsModelSet);
            var file = Assert.IsAssignableFrom<IFormFile>(result.Model);
            
            ContentDispositionHeaderValue contentDisposition;
            ContentDispositionHeaderValue.TryParse(file.ContentDisposition, out contentDisposition);
            Assert.Equal(expected, contentDisposition.Name);
        }
Пример #37
0
        public async Task FormFileModelBinder_ReturnsNoResult_WhenNamesDontMatch()
        {
            // Arrange
            var formFiles = new FormFileCollection();
            formFiles.Add(GetMockFormFile("different name", "file1.txt"));
            var httpContext = GetMockHttpContext(GetMockFormCollection(formFiles));
            var bindingContext = GetBindingContext(typeof(IFormFile), httpContext);
            var binder = new FormFileModelBinder();

            // Act
            var result = await binder.BindModelAsync(bindingContext);

            // Assert
            Assert.NotEqual(ModelBindingResult.NoResult, result);
            Assert.Null(result.Model);
        }
        public void WithFormShouldWorkCorrectly()
        {
            var stream = new MemoryStream();
            var files = new FormFileCollection
            {
                new FormFile(stream, 0, 0, "FirstFile", "FirstFileName"),
                new FormFile(stream, 0, 0, "SecondFile", "SecondFileName"),
            };

            MyController<MvcController>
                .Instance()
                .WithHttpRequest(request => request
                    .WithForm(new FormCollection(
                        new Dictionary<string, StringValues>
                        {
                            ["Field"] = new StringValues("FieldValue"),
                            ["AnotherField"] = new StringValues(new[] { "AnotherFieldValue", "SecondFieldValue" }),
                        },
                        files)))
                .ShouldPassForThe<HttpRequest>(builtRequest =>
                {
                    Assert.Equal(2, builtRequest.Form.Count);
                    Assert.Equal("FieldValue", builtRequest.Form["Field"]);
                    Assert.Equal("AnotherFieldValue,SecondFieldValue", builtRequest.Form["AnotherField"]);
                    Assert.Equal(2, builtRequest.Form.Files.Count);
                    Assert.Same(files[0], builtRequest.Form.Files[0]);
                    Assert.Same(files[1], builtRequest.Form.Files[1]);
                });
        }
        private void UpdateRequest(HttpRequest request, string data, string name)
        {
            const string fileName = "text.txt";
            var fileCollection = new FormFileCollection();
            var formCollection = new FormCollection(new Dictionary<string, StringValues>(), fileCollection);

            request.Form = formCollection;
            request.ContentType = "multipart/form-data; boundary=----WebKitFormBoundarymx2fSWqWSd0OxQqq";

            if (string.IsNullOrEmpty(data) || string.IsNullOrEmpty(name))
            {
                // Leave the submission empty.
                return;
            }

            request.Headers["Content-Disposition"] = $"form-data; name={name}; filename={fileName}";

            var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(data));
            fileCollection.Add(new FormFile(memoryStream, 0, data.Length, name, fileName)
            {
                Headers = request.Headers
            });
        }
        private static void SetFormFileBodyContent(HttpRequest request, string content, string name)
        {
            const string fileName = "text.txt";
            var fileCollection = new FormFileCollection();
            var formCollection = new FormCollection(new Dictionary<string, StringValues>(), fileCollection);
            var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(content));

            request.Form = formCollection;
            request.ContentType = "multipart/form-data; boundary=----WebKitFormBoundarymx2fSWqWSd0OxQqq";
            request.Headers["Content-Disposition"] = $"form-data; name={name}; filename={fileName}";

            fileCollection.Add(new FormFile(memoryStream, 0, memoryStream.Length, name, fileName)
            {
                Headers = request.Headers
            });
        }
Пример #41
0
 public FormCollection(IDictionary<string, string[]> store, FormFileCollection files)
     : base(store)
 {
     Files = files;
 }
Пример #42
0
        public async Task FormFileModelBinder_ReturnsNoResult_WithNoFileNameAndZeroLength()
        {
            // Arrange
            var formFiles = new FormFileCollection();
            formFiles.Add(GetMockFormFile("file", ""));
            var httpContext = GetMockHttpContext(GetMockFormCollection(formFiles));
            var bindingContext = GetBindingContext(typeof(IFormFile), httpContext);
            var binder = new FormFileModelBinder();

            // Act
            var result = await binder.BindModelAsync(bindingContext);

            // Assert
            Assert.NotEqual(ModelBindingResult.NoResult, result);
            Assert.Null(result.Model);
        }
Пример #43
0
 private static IFormCollection GetMockFormCollection(FormFileCollection formFiles)
 {
     var formCollection = new Mock<IFormCollection>();
     formCollection.Setup(f => f.Files).Returns(formFiles);
     return formCollection.Object;
 }
        private void UpdateRequest(HttpRequest request, string data, string name)
        {
            var fileCollection = new FormFileCollection();
            var formCollection = new FormCollection(new Dictionary<string, string[]>(), fileCollection);
            var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(data));

            request.Form = formCollection;
            request.ContentType = "multipart/form-data; boundary=----WebKitFormBoundarymx2fSWqWSd0OxQqq";
            request.Headers["Content-Disposition"] = "form-data; name=" + name + "; filename=text.txt";
            fileCollection.Add(new FormFile(memoryStream, 0, data.Length)
            {
                Headers = request.Headers
            });
        }
Пример #45
0
        public async Task<IFormCollection> ReadFormAsync(CancellationToken cancellationToken)
        {
            if (Form != null)
            {
                return Form;
            }

            if (!HasFormContentType)
            {
                throw new InvalidOperationException("Incorrect Content-Type: " + _request.ContentType);
            }

            cancellationToken.ThrowIfCancellationRequested();

            _request.EnableRewind();

            IDictionary<string, StringValues> formFields = null;
            var files = new FormFileCollection();

            // Some of these code paths use StreamReader which does not support cancellation tokens.
            using (cancellationToken.Register(_request.HttpContext.Abort))
            {
                var contentType = ContentType;
                // Check the content-type
                if (HasApplicationFormContentType(contentType))
                {
                    var encoding = FilterEncoding(contentType.Encoding);
                    formFields = await FormReader.ReadFormAsync(_request.Body, encoding, cancellationToken);
                }
                else if (HasMultipartFormContentType(contentType))
                {
                    var formAccumulator = new KeyValueAccumulator();

                    var boundary = GetBoundary(contentType);
                    var multipartReader = new MultipartReader(boundary, _request.Body);
                    var section = await multipartReader.ReadNextSectionAsync(cancellationToken);
                    while (section != null)
                    {
                        var headers = new HeaderDictionary(section.Headers);
                        ContentDispositionHeaderValue contentDisposition;
                        ContentDispositionHeaderValue.TryParse(headers[HeaderNames.ContentDisposition], out contentDisposition);
                        if (HasFileContentDisposition(contentDisposition))
                        {
                            // Find the end
                            await section.Body.DrainAsync(cancellationToken);

                            var file = new FormFile(_request.Body, section.BaseStreamOffset.Value, section.Body.Length)
                            {
                                Headers = headers,
                            };
                            files.Add(file);
                        }
                        else if (HasFormDataContentDisposition(contentDisposition))
                        {
                            // Content-Disposition: form-data; name="key"
                            //
                            // value

                            var key = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
                            MediaTypeHeaderValue mediaType;
                            MediaTypeHeaderValue.TryParse(headers[HeaderNames.ContentType], out mediaType);
                            var encoding = FilterEncoding(mediaType?.Encoding);
                            using (var reader = new StreamReader(section.Body, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true))
                            {
                                var value = await reader.ReadToEndAsync();
                                formAccumulator.Append(key, value);
                            }
                        }
                        else
                        {
                            System.Diagnostics.Debug.Assert(false, "Unrecognized content-disposition for this section: " + headers[HeaderNames.ContentDisposition]);
                        }

                        section = await multipartReader.ReadNextSectionAsync(cancellationToken);
                    }

                    formFields = formAccumulator.GetResults();
                }
            }

            // Rewind so later readers don't have to.
            _request.Body.Seek(0, SeekOrigin.Begin);

            Form = new FormCollection(formFields, files);
            return Form;
        }
        private static void SetFormFileBodyContent(HttpRequest request, string content, string name)
        {
            var fileCollection = new FormFileCollection();
            var formCollection = new FormCollection(new Dictionary<string, string[]>(), fileCollection);
            var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(content));

            request.Form = formCollection;
            request.ContentType = "multipart/form-data";
            request.Headers["Content-Disposition"] = "form-data; name=" + name + "; filename=text.txt";

            fileCollection.Add(new FormFile(memoryStream, 0, memoryStream.Length)
            {
                Headers = request.Headers
            });
        }
Пример #47
0
        private async Task<IFormCollection> InnerReadFormAsync(CancellationToken cancellationToken)
        {
            if (!HasFormContentType)
            {
                throw new InvalidOperationException("Incorrect Content-Type: " + _request.ContentType);
            }

            cancellationToken.ThrowIfCancellationRequested();

            if (_options.BufferBody)
            {
                _request.EnableRewind(_options.MemoryBufferThreshold, _options.BufferBodyLengthLimit);
            }

            FormCollection formFields = null;
            FormFileCollection files = null;

            // Some of these code paths use StreamReader which does not support cancellation tokens.
            using (cancellationToken.Register((state) => ((HttpContext)state).Abort(), _request.HttpContext))
            {
                var contentType = ContentType;
                // Check the content-type
                if (HasApplicationFormContentType(contentType))
                {
                    var encoding = FilterEncoding(contentType.Encoding);
                    using (var formReader = new FormReader(_request.Body, encoding)
                    {
                        ValueCountLimit = _options.ValueCountLimit,
                        KeyLengthLimit = _options.KeyLengthLimit,
                        ValueLengthLimit = _options.ValueLengthLimit,
                    })
                    {
                        formFields = new FormCollection(await formReader.ReadFormAsync(cancellationToken));
                    }
                }
                else if (HasMultipartFormContentType(contentType))
                {
                    var formAccumulator = new KeyValueAccumulator();

                    var boundary = GetBoundary(contentType, _options.MultipartBoundaryLengthLimit);
                    var multipartReader = new MultipartReader(boundary, _request.Body)
                    {
                        HeadersCountLimit = _options.MultipartHeadersCountLimit,
                        HeadersLengthLimit = _options.MultipartHeadersLengthLimit,
                        BodyLengthLimit = _options.MultipartBodyLengthLimit,
                    };
                    var section = await multipartReader.ReadNextSectionAsync(cancellationToken);
                    while (section != null)
                    {
                        ContentDispositionHeaderValue contentDisposition;
                        ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition);
                        if (HasFileContentDisposition(contentDisposition))
                        {
                            // Enable buffering for the file if not already done for the full body
                            section.EnableRewind(_request.HttpContext.Response.RegisterForDispose,
                                _options.MemoryBufferThreshold, _options.MultipartBodyLengthLimit);
                            // Find the end
                            await section.Body.DrainAsync(cancellationToken);

                            var name = HeaderUtilities.RemoveQuotes(contentDisposition.Name) ?? string.Empty;
                            var fileName = HeaderUtilities.RemoveQuotes(contentDisposition.FileName) ?? string.Empty;

                            FormFile file;
                            if (section.BaseStreamOffset.HasValue)
                            {
                                // Relative reference to buffered request body
                                file = new FormFile(_request.Body, section.BaseStreamOffset.Value, section.Body.Length, name, fileName);
                            }
                            else
                            {
                                // Individually buffered file body
                                file = new FormFile(section.Body, 0, section.Body.Length, name, fileName);
                            }
                            file.Headers = new HeaderDictionary(section.Headers);

                            if (files == null)
                            {
                                files = new FormFileCollection();
                            }
                            if (files.Count >= _options.ValueCountLimit)
                            {
                                throw new InvalidDataException($"Form value count limit {_options.ValueCountLimit} exceeded.");
                            }
                            files.Add(file);
                        }
                        else if (HasFormDataContentDisposition(contentDisposition))
                        {
                            // Content-Disposition: form-data; name="key"
                            //
                            // value

                            // Do not limit the key name length here because the mulipart headers length limit is already in effect.
                            var key = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
                            MediaTypeHeaderValue mediaType;
                            MediaTypeHeaderValue.TryParse(section.ContentType, out mediaType);
                            var encoding = FilterEncoding(mediaType?.Encoding);
                            using (var reader = new StreamReader(section.Body, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true))
                            {
                                // The value length limit is enforced by MultipartBodyLengthLimit
                                var value = await reader.ReadToEndAsync();
                                formAccumulator.Append(key, value);
                                if (formAccumulator.ValueCount > _options.ValueCountLimit)
                                {
                                    throw new InvalidDataException($"Form value count limit {_options.ValueCountLimit} exceeded.");
                                }
                            }
                        }
                        else
                        {
                            System.Diagnostics.Debug.Assert(false, "Unrecognized content-disposition for this section: " + section.ContentDisposition);
                        }

                        section = await multipartReader.ReadNextSectionAsync(cancellationToken);
                    }

                    if (formAccumulator.HasValues)
                    {
                        formFields = new FormCollection(formAccumulator.GetResults(), files);
                    }
                }
            }

            // Rewind so later readers don't have to.
            if (_request.Body.CanSeek)
            {
                _request.Body.Seek(0, SeekOrigin.Begin);
            }

            if (formFields != null)
            {
                Form = formFields;
            }
            else if (files != null)
            {
                Form = new FormCollection(null, files);
            }
            else
            {
                Form = FormCollection.Empty;
            }

            return Form;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MockedHttpRequest"/> class.
        /// </summary>
        public MockedHttpRequest(HttpContext httpContext)
        {
            CommonValidator.CheckForNullReference(httpContext, nameof(HttpContext));

            this.httpContext = httpContext;
            this.headerDictionary = new HeaderDictionary();
            this.formFiles = new FormFileCollection();
            this.cookieValues = new Dictionary<string, string>();
            this.formValues = new Dictionary<string, StringValues>();
            this.queryValues = new Dictionary<string, StringValues>();
        }