Esempio n. 1
0
        public void MultipartRequestHelperTest_HasFormDataContentDispositionTrue()
        {
            var formdata =
                new Microsoft.Net.Http.Headers.ContentDispositionHeaderValue("form-data");

            Assert.AreEqual(true, MultipartRequestHelper.HasFormDataContentDisposition(formdata));
        }
Esempio n. 2
0
        public void MultipartRequestHelperTest_HasFormDataContentDispositionFalse()
        {
            var formdata =
                new Microsoft.Net.Http.Headers.ContentDispositionHeaderValue("form-data");

            formdata.FileName     = "test";
            formdata.FileNameStar = "1";
            Assert.AreEqual("form-data; filename=test; filename*=UTF-8''1", formdata.ToString());
            Assert.AreEqual(false, MultipartRequestHelper.HasFormDataContentDisposition(formdata));
        }
Esempio n. 3
0
        public async Task <IActionResult> UploadImageLarge()
        {
            try
            {
                if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
                {
                    return(BadRequest(string.Format(MessagesConstants.ExpectedDifferentRequest, Request.ContentType)));
                }
                // Used to accumulate all the form url encoded key value pairs in the
                // request.
                var    formAccumulator = new KeyValueAccumulator();
                string targetFilePath  = null;

                var boundary = MultipartRequestHelper.GetBoundary(
                    MediaTypeHeaderValue.Parse(Request.ContentType),
                    _defaultFormOptions.MultipartBoundaryLengthLimit);
                var reader = new MultipartReader(boundary, HttpContext.Request.Body);

                var section = await reader.ReadNextSectionAsync();

                while (section != null)
                {
                    ContentDispositionHeaderValue contentDisposition;
                    var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition);

                    if (hasContentDispositionHeader)
                    {
                        if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                        {
                            targetFilePath = Path.GetTempFileName();
                            using (var targetStream = System.IO.File.Create(targetFilePath))
                            {
                                await section.Body.CopyToAsync(targetStream);
                            }
                        }
                        else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                        {
                            formAccumulator = await UploadImageLargeRefactor(formAccumulator, section, contentDisposition);
                        }
                    }

                    // Drains any remaining section body that has not been consumed and
                    // reads the headers for the next section.
                    section = await reader.ReadNextSectionAsync();
                }

                return(Ok(new ApiResponse(Microsoft.AspNetCore.Http.StatusCodes.Status200OK, true, "Image Uploaded Successfully.", targetFilePath)));
            }
            catch (Exception ex)
            {
                HttpContext.RiseError(new Exception(string.Concat("API := (Image := UploadImageLarge)", ex.Message, " Stack Trace : ", ex.StackTrace, " Inner Exception : ", ex.InnerException)));
                return(Ok(someIssueInProcessing));
            }
        }
        public static async Task <LocalMultipartFormData> CreateAsync(HttpRequest request, string folderPath,
                                                                      Func <string, MultipartSection, MultipartFileInfo, Task <string> > fileHandle)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            if (!MultipartRequestHelper.IsMultipartContentType(request.ContentType))
            {
                throw new InvalidDataException("Request is not a multipart request");
            }

            var files           = new List <LocalMultipartFileInfo>();
            var formAccumulator = new KeyValueAccumulator();
            var reader          = GetMultipartReader(request);

            var section = await reader.ReadNextSectionAsync();

            while (section != null)
            {
                var hasContentDispositionHeader =
                    ContentDispositionHeaderValue.TryParse(
                        section.ContentDisposition,
                        out ContentDispositionHeaderValue contentDisposition);

                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        var formFile = new MultipartFileInfo {
                            Name     = section.AsFileSection().Name,
                            FileName = section.AsFileSection().FileName,
                            Length   = section.Body.Length
                        };

                        var savingPath = await fileHandle(folderPath, section, formFile);

                        files.Add(new LocalMultipartFileInfo(formFile)
                        {
                            TemporaryLocation = savingPath
                        });
                    }
                    else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                    {
                        formAccumulator = await AccumulateForm(formAccumulator, section, contentDisposition);
                    }
                }

                section = await reader.ReadNextSectionAsync();
            }

            return(new LocalMultipartFormData(formAccumulator.GetResults(), files));
        }
Esempio n. 5
0
        public async Task <IActionResult> UploadB()
        {
            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                return(BadRequest("WTF"));
            }
            var formAccumulator = new KeyValueAccumulator();
            var boundary        = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType), 10000);
            var reader          = new MultipartReader(boundary, HttpContext.Request.Body);
            var section         = await reader.ReadNextSectionAsync();

            while (section != null)
            {
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);
                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        var targetFilePath = (Path.Combine(tempPath, Guid.NewGuid().ToString("N") + ".pdf"));
                        using (var targetStream = System.IO.File.Create(targetFilePath)) {
                            await section.Body.CopyToAsync(targetStream);
                        }
                    }
                    else if (false && MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                    {
                        var key      = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
                        var encoding = GetEncoding(section);
                        using (var streamReader = new StreamReader(
                                   section.Body,
                                   encoding,
                                   detectEncodingFromByteOrderMarks: true,
                                   bufferSize: 1024,
                                   leaveOpen: true
                                   )) {
                            var value = await streamReader.ReadToEndAsync();

                            if (String.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
                            {
                                value = string.Empty;
                            }
                            formAccumulator.Append(key.ToString(), value);

                            if (formAccumulator.ValueCount > 100)
                            {
                                throw new InvalidDataException("Form WTF");
                            }
                        }
                    }
                }
                section = await reader.ReadNextSectionAsync();
            }
            return(Ok(new { Success = true }));
        }
Esempio n. 6
0
            public async Task <DigitalAssetResponse> Handle(Command command, CancellationToken cancellationToken)
            {
                var httpContext        = __httpContextAccessor.HttpContext;
                var defaultFormOptions = new FormOptions();
                var digitalAssets      = new List <DigitalAsset>();
                var contentType        = httpContext.Request.ContentType;

                if (!MultipartRequestHelper.IsMultipartContentType(contentType))
                {
                    throw new Exception($"Expected a multipart request, but got { contentType }");
                }

                var mediaTypeHeaderValue = MediaTypeHeaderValue.Parse(contentType);
                var boundary             = MultipartRequestHelper.GetBoundary(
                    mediaTypeHeaderValue, defaultFormOptions.MultipartBoundaryLengthLimit
                    );
                var reader  = new MultipartReader(boundary, httpContext.Request.Body);
                var section = await reader.ReadNextSectionAsync(cancellationToken);

                while (section != null)
                {
                    var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out ContentDispositionHeaderValue contentDisposition);

                    if (hasContentDispositionHeader)
                    {
                        if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                        {
                            using var targetStream = new MemoryStream();
                            await section.Body.CopyToAsync(targetStream, cancellationToken);

                            var name  = $"{ contentDisposition.FileName }".Trim(new char[] { '"' }).Replace("&", "and");
                            var bytes = StreamHelper.ReadToEnd(targetStream);
                            var sectionContentType = section.ContentType;
                            var digitalAsset       = new DigitalAsset(name, bytes, sectionContentType);

                            _databaseContext.Store(digitalAsset);
                            digitalAssets.Add(digitalAsset);
                        }
                    }

                    section = await reader.ReadNextSectionAsync(cancellationToken);
                }

                await _databaseContext.SaveChangesAsync(cancellationToken);

                return(new DigitalAssetResponse()
                {
                    DigitalAssetsIds = digitalAssets.Select(x => x.DigitalAssetId).ToList()
                });
            }
Esempio n. 7
0
        private async Task <FilesAndFormData> ParseMultipartRequest()
        {
            var filesAndFormData = new FilesAndFormData {
                Files = new List <UploadedTempFile>()
            };
            var formAccumulator = new KeyValueAccumulator();

            var boundary = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(Request.ContentType),
                _defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader = new MultipartReader(boundary.Value, HttpContext.Request.Body);

            var section = await reader.ReadNextSectionAsync();

            while (section != null)
            {
                if (ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition))
                {
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        var tempFileName = await fileService.CreateTempFile(section.Body);

                        filesAndFormData.Files.Add(new UploadedTempFile {
                            OriginalName = contentDisposition.FileName.Value,
                            TempFileName = tempFileName
                        });
                    }
                    else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                    {
                        var(key, value) = await ParseFormDataSection(formAccumulator, section, contentDisposition);

                        formAccumulator.Append(key, value);

                        if (formAccumulator.ValueCount > _defaultFormOptions.ValueCountLimit)
                        {
                            throw new InvalidDataException($"Form key count limit {_defaultFormOptions.ValueCountLimit} exceeded.");
                        }
                    }
                }

                // Drains any remaining section body that has not been consumed and
                // reads the headers for the next section.
                section = await reader.ReadNextSectionAsync();
            }

            filesAndFormData.FormData = new FormCollection(formAccumulator.GetResults());
            return(filesAndFormData);
        }
Esempio n. 8
0
        //[DisableFormValueModelBinding]
        //[ValidateAntiForgeryToken]
        public async Task <IActionResult> Upload()
        {
            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                return(BadRequest($"Expected a multipart request, but got {Request.ContentType}"));
            }

            // Used to accumulate all the form url encoded key value pairs in the
            // request.
            var    formAccumulator = new KeyValueAccumulator();
            string targetFilePath  = null;

            var boundary = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(Request.ContentType),
                _defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader = new MultipartReader(boundary, HttpContext.Request.Body);

            var section = await reader.ReadNextSectionAsync();

            while (section != null)
            {
                ContentDispositionHeaderValue contentDisposition;
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition,
                                                                                         out contentDisposition);

                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        targetFilePath = Path.GetTempFileName();
                        using (var targetStream = System.IO.File.Create(targetFilePath))
                        {
                            await section.Body.CopyToAsync(targetStream);

                            LogHelper.Info($"Copied the uploaded file '{targetFilePath}'");
                        }
                    }
                    else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                    {
                        // Content-Disposition: form-data; name="key"
                        //
                        // value

                        // Do not limit the key name length here because the
                        // multipart headers length limit is already in effect.
                        var key      = HeaderUtilities.RemoveQuotes(contentDisposition.Name).Value;
                        var encoding = GetEncoding(section);
                        using (var streamReader = new StreamReader(
                                   section.Body,
                                   encoding,
                                   detectEncodingFromByteOrderMarks: true,
                                   bufferSize: 1024,
                                   leaveOpen: true))
                        {
                            // The value length limit is enforced by MultipartBodyLengthLimit
                            var value = await streamReader.ReadToEndAsync();

                            if (String.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
                            {
                                value = String.Empty;
                            }
                            formAccumulator.Append(key, value);

                            if (formAccumulator.ValueCount > _defaultFormOptions.ValueCountLimit)
                            {
                                throw new InvalidDataException($"Form key count limit {_defaultFormOptions.ValueCountLimit} exceeded.");
                            }
                        }
                    }
                }

                // Drains any remaining section body that has not been consumed and
                // reads the headers for the next section.
                section = await reader.ReadNextSectionAsync();
            }

            // Bind form data to a model
            var formValueProvider = new FormValueProvider(
                BindingSource.Form,
                new FormCollection(formAccumulator.GetResults()),
                CultureInfo.CurrentCulture);

            //var bindingSuccessful = await TryUpdateModelAsync(user, prefix: "",
            //    valueProvider: formValueProvider);
            //if (!bindingSuccessful)
            //{
            //    if (!ModelState.IsValid)
            //    {
            //        return BadRequest(ModelState);
            //    }
            //}

            return(Json(new
            {
                FilePath = targetFilePath
            }));
        }
Esempio n. 9
0
        public async Task <IActionResult> UploadDatabase()
        {
            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                ModelState.AddModelError("File",
                                         $"The request couldn't be processed (Error 1).");
                // Log error

                return(BadRequest(ModelState));
            }

            // Accumulate the form data key-value pairs in the request (formAccumulator).
            var formAccumulator               = new KeyValueAccumulator();
            var trustedFileNameForDisplay     = string.Empty;
            var untrustedFileNameForStorage   = string.Empty;
            var trustedFilePathStorage        = string.Empty;
            var trustedFileNameForFileStorage = string.Empty;
            var streamedFileContent           = new byte[0];
            var streamedFilePhysicalContent   = new byte[0];

            // List Byte for file storage
            List <byte[]> filesByteStorage         = new List <byte[]>();
            List <string> filesNameStorage         = new List <string>();
            var           fileStoredData           = new Dictionary <string, byte[]>();
            List <string> storedPaths              = new List <string>();
            List <string> storedPathDictionaryKeys = new List <string>();

            // List to Submit
            List <ClamSectionAcademicSubCategoryItem> itemList = new List <ClamSectionAcademicSubCategoryItem>();

            var boundary = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(Request.ContentType),
                _defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader = new MultipartReader(boundary, HttpContext.Request.Body);

            var section = await reader.ReadNextSectionAsync();

            while (section != null)
            {
                var hasContentDispositionHeader =
                    ContentDispositionHeaderValue.TryParse(
                        section.ContentDisposition, out var contentDisposition);

                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper
                        .HasFileContentDisposition(contentDisposition))
                    {
                        untrustedFileNameForStorage = contentDisposition.FileName.Value;
                        // Don't trust the file name sent by the client. To display
                        // the file name, HTML-encode the value.
                        trustedFileNameForDisplay = WebUtility.HtmlEncode(
                            contentDisposition.FileName.Value);

                        if (!Directory.Exists(_targetFilePath))
                        {
                            string path = String.Format("{0}", _targetFilePath);
                            Directory.CreateDirectory(path);
                        }

                        //streamedFileContent =
                        //    await FileHelpers.ProcessStreamedFile(section, contentDisposition,
                        //        ModelState, _permittedExtentions, _fileSizeLimit);

                        streamedFilePhysicalContent = await FileHelpers.ProcessStreamedFile(
                            section, contentDisposition, ModelState,
                            _permittedExtentions, _fileSizeLimit);

                        filesNameStorage.Add(trustedFileNameForDisplay);
                        filesByteStorage.Add(streamedFilePhysicalContent);
                        fileStoredData.Add(trustedFileNameForDisplay, streamedFilePhysicalContent);

                        if (!ModelState.IsValid)
                        {
                            return(BadRequest(ModelState));
                        }
                    }
                    else if (MultipartRequestHelper
                             .HasFormDataContentDisposition(contentDisposition))
                    {
                        // Don't limit the key name length because the
                        // multipart headers length limit is already in effect.
                        var key = HeaderUtilities
                                  .RemoveQuotes(contentDisposition.Name).Value;
                        var encoding = GetEncoding(section);

                        if (encoding == null)
                        {
                            ModelState.AddModelError("File",
                                                     $"The request couldn't be processed (Error 2).");
                            // Log error

                            return(BadRequest(ModelState));
                        }

                        using (var streamReader = new StreamReader(
                                   section.Body,
                                   encoding,
                                   detectEncodingFromByteOrderMarks: true,
                                   bufferSize: 1024,
                                   leaveOpen: true))
                        {
                            // The value length limit is enforced by
                            // MultipartBodyLengthLimit
                            var value = await streamReader.ReadToEndAsync();

                            if (string.Equals(value, "undefined",
                                              StringComparison.OrdinalIgnoreCase))
                            {
                                value = string.Empty;
                            }

                            formAccumulator.Append(key, value);

                            if (formAccumulator.ValueCount >
                                _defaultFormOptions.ValueCountLimit)
                            {
                                // Form key count limit of
                                // _defaultFormOptions.ValueCountLimit
                                // is exceeded.
                                ModelState.AddModelError("File",
                                                         $"The request couldn't be processed (Error 3).");
                                // Log error

                                return(BadRequest(ModelState));
                            }
                        }
                    }
                }

                // Drain any remaining section body that hasn't been consumed and
                // read the headers for the next section.
                section = await reader.ReadNextSectionAsync();
            }

            // Bind form data to the model
            var formData          = new FormData();
            var formValueProvider = new FormValueProvider(
                BindingSource.Form,
                new FormCollection(formAccumulator.GetResults()),
                CultureInfo.CurrentCulture);
            var bindingSuccessful = await TryUpdateModelAsync(formData, prefix : "",
                                                              valueProvider : formValueProvider);

            //trustedFilePathStorage = String.Format("{0}\\{1}\\{2}\\{3}",
            //    //_targetFilePath,
            //    _targetFolderPath,
            //    formData.AcademicId,
            //    formData.SubCategoryId,
            //    Path.GetRandomFileName());

            if (!bindingSuccessful)
            {
                ModelState.AddModelError("File",
                                         "The request couldn't be processed (Error 5).");
                // Log error

                return(BadRequest(ModelState));
            }

            // **WARNING!**
            // In the following example, the file is saved without
            // scanning the file's contents. In most production
            // scenarios, an anti-virus/anti-malware scanner API
            // is used on the file before making the file available
            // for download or for use by other systems.
            // For more information, see the topic that accompanies
            // this sample app.

            foreach (var item in fileStoredData)
            {
                trustedFilePathStorage = String.Format("{0}\\{1}\\{2}\\{3}",
                                                       _targetFolderPath,
                                                       formData.AcademicId,
                                                       formData.SubCategoryId,
                                                       Path.GetRandomFileName());
                Directory.CreateDirectory(trustedFilePathStorage);

                using (var targetStream = System.IO.File.Create(
                           Path.Combine(trustedFilePathStorage, item.Key)))
                {
                    await targetStream.WriteAsync(item.Value);

                    _logger.LogInformation(
                        "Uploaded file '{TrustedFileNameForDisplay}' saved to " +
                        "'{TargetFilePath}' as {TrustedFileNameForFileStorage}",
                        item.Key, trustedFilePathStorage,
                        item.Key);
                }

                itemList.Add(new ClamSectionAcademicSubCategoryItem()
                {
                    ItemPath  = Path.Combine(trustedFilePathStorage, item.Key),
                    ItemTitle = item.Key,
                    //ItemDescription = formData.Note,
                    Size          = item.Value.Length,
                    DateAdded     = DateTime.Now,
                    SubCategoryId = formData.SubCategoryId,
                    AcademicId    = formData.AcademicId
                });
            }


            //using (var targetStream = System.IO.File.Create(
            //                Path.Combine(trustedFilePathStorage, trustedFileNameForDisplay)))
            //{
            //    await targetStream.WriteAsync(streamedFilePhysicalContent);

            //    _logger.LogInformation(
            //        "Uploaded file '{TrustedFileNameForDisplay}' saved to " +
            //        "'{TargetFilePath}' as {TrustedFileNameForFileStorage}",
            //        trustedFileNameForDisplay, trustedFilePathStorage,
            //        trustedFileNameForDisplay);
            //}

            //var file = new ClamSectionAcademicSubCategoryItem()
            //{
            //    ItemPath = Path.Combine(trustedFilePathStorage, trustedFileNameForDisplay),
            //    ItemTitle = untrustedFileNameForStorage,
            //    //ItemDescription = formData.Note,
            //    Size = streamedFilePhysicalContent.Length,
            //    DateAdded = DateTime.Now,
            //    SubCategoryId = formData.SubCategoryId,
            //    AcademicId = formData.AcademicId
            //};

            await _context.AddRangeAsync(itemList);

            await _context.SaveChangesAsync();

            return(RedirectToAction("Episode", "Academia", new { id = formData.AcademicId, said = formData.SubCategoryId }));
        }
Esempio n. 10
0
        public async Task <IActionResult> ImportFile()
        {
            try
            {
                try
                {
                    if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
                    {
                        return(BadRequest($"Expected a multipart request, but got {Request.ContentType}"));
                    }
                    var queryString = Request.Query;

                    /*
                     *  Sacamos la ruta de la carpeta para importar medios de contactos
                     */

                    var parameter = new Common.GblParameter();
                    parameter.SEARCH_KEY = "IMPORT_PRODUCT_PENDING";

                    var message = new Message();
                    message.BusinessLogic = configuration.GetValue <string>("AppSettings:BusinessLogic:GblParameter");
                    message.Connection    = configuration.GetValue <string>("ConnectionStrings:MEXPRESS_AC");
                    message.Operation     = Operation.Get;
                    using (var businessLgic = new ServiceManager())
                    {
                        message.MessageInfo = parameter.SerializeObject();
                        var parameterResult = await businessLgic.DoWork(message);

                        if (parameterResult.Status == Status.Failed)
                        {
                            return(BadRequest(parameterResult.Result));
                        }
                        parameter = parameterResult.DeSerializeObject <Common.GblParameter>();
                    }



                    // Used to accumulate all the form url encoded key value pairs in the
                    // request.

                    var    formAccumulator      = new KeyValueAccumulator();
                    var    nameFile             = String.Empty;
                    string targetFilePathBackUp = string.Empty;
                    string targetFilePath       = string.Empty;
                    var    boundary             = MultipartRequestHelper.GetBoundary(
                        Microsoft.Net.Http.Headers.MediaTypeHeaderValue.Parse(Request.ContentType),
                        _defaultFormOptions.MultipartBoundaryLengthLimit);
                    var reader = new MultipartReader(boundary, HttpContext.Request.Body);

                    var section = await reader.ReadNextSectionAsync();

                    while (section != null)
                    {
                        Microsoft.Net.Http.Headers.ContentDispositionHeaderValue contentDisposition;
                        var hasContentDispositionHeader = Microsoft.Net.Http.Headers.ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition);

                        if (hasContentDispositionHeader)
                        {
                            if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                            {
                                var date    = DateTime.Now;
                                var dateNow = date.Year.ToString() + "_" + date.Month.ToString() + "_" + date.Day.ToString() + "_" + date.Hour.ToString() + "_" + date.Minute.ToString() + "_" + date.Millisecond.ToString();
                                nameFile             = configuration.GetValue <string>("Files:FileName");
                                targetFilePathBackUp = string.Format("{0}{1}_{2}{3}", parameter.VALUE, nameFile, dateNow, ".xlsx");
                                nameFile             = string.Format("{0}_{1}{2}", nameFile, dateNow, ".xlsx");
                                if (!System.IO.File.Exists(targetFilePath))
                                {
                                    if (!Directory.Exists(parameter.VALUE))
                                    {
                                        Directory.CreateDirectory(parameter.VALUE);
                                    }
                                }


                                using (var targetStream = System.IO.File.Create(targetFilePathBackUp))
                                {
                                    await section.Body.CopyToAsync(targetStream);
                                }
                            }
                            else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                            {
                                var key      = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
                                var encoding = GetEncoding(section);
                                using (var streamReader = new StreamReader(
                                           section.Body,
                                           encoding,
                                           detectEncodingFromByteOrderMarks: true,
                                           bufferSize: 1024,
                                           leaveOpen: true))
                                {
                                    // The value length limit is enforced by MultipartBodyLengthLimit
                                    var value = await streamReader.ReadToEndAsync();

                                    if (String.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
                                    {
                                        value = String.Empty;
                                    }
                                    formAccumulator.Append(key.Value, value);

                                    if (formAccumulator.ValueCount > _defaultFormOptions.ValueCountLimit)
                                    {
                                        throw new InvalidDataException($"Form key count limit {_defaultFormOptions.ValueCountLimit} exceeded.");
                                    }
                                }
                            }
                        }

                        // Drains any remaining section body that has not been consumed and
                        // reads the headers for the next section.
                        section = await reader.ReadNextSectionAsync();
                    }

                    var model = new Common.Import_Product();
                    model = GetHeaderPk(formAccumulator.GetResults());
                    model.Creation_User = (queryString["User"]).ToString();
                    model.File_Path     = ProcessPathDocumentAsync(nameFile, targetFilePathBackUp).Result;

                    var formValueProvider = new FormValueProvider(
                        BindingSource.Form,
                        new FormCollection(formAccumulator.GetResults()),
                        CultureInfo.CurrentCulture);

                    var bindingSuccessful = await TryUpdateModelAsync(model, prefix : "",
                                                                      valueProvider : formValueProvider);


                    message.BusinessLogic = configuration.GetValue <string>("AppSettings:BusinessLogic:Gbl_Wrk_Agreement_Detail");
                    message.Connection    = configuration.GetValue <string>("ConnectionStrings:MEXPRESS_AC");
                    message.Operation     = Operation.Save;
                    using (var businessLgic = new ServiceManager())
                    {
                        message.MessageInfo = model.SerializeObject();
                        var result = await businessLgic.DoWork(message);

                        if (result.Status == Status.Failed)
                        {
                            return(BadRequest(result.Result));
                        }
                        var list = result.DeSerializeObject <IEnumerable <Common.Import_Product> >();

                        return(Ok(list));
                    }
                }
                catch (Exception ex)
                {
                    return(BadRequest(ex));
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(ex));
            }
        }
        public async Task <HttpResponseMessage> PostFiles([FromForm] string value)
        {
            FormOptions _defaultFormOptions = new FormOptions();

            DateTime methodStartTimeStamp = DateTime.Now;

            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Created);

            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                response = GetResponseMessage(HttpStatusCode.BadRequest, MessageConstant.MimePartErrorMessage);
                return(response);
            }

            var formAccumulator = new KeyValueAccumulator();

            var boundary = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(Request.ContentType),
                _defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader = new MultipartReader(boundary, HttpContext.Request.Body);

            var section = await reader.ReadNextSectionAsync();

            string targetFilePath = string.Empty;

            var attachmentList = new List <Attachment>();

            while (section != null)
            {
                ContentDispositionHeaderValue contentDisposition;
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition);

                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        var rootPath = _configuration["SharedLocation:RootPath"].ToString();
                        try
                        {
                            var directoryInfo = Directory.CreateDirectory(Path.Combine(rootPath, Guid.NewGuid().ToString()));

                            targetFilePath = directoryInfo.FullName + "//" + section.AsFileSection().FileName;
                            var bodyStream = new MemoryStream();
                            section.Body.CopyTo(bodyStream);
                            byte[] attachmentData = new byte[bodyStream.Length];
                            attachmentList.Add(new Attachment()
                            {
                                FileName = section.AsFileSection().FileName,
                                FileData = bodyStream.ToArray()
                            });

                            using (var targetStream = System.IO.File.Create(targetFilePath))
                            {
                                bodyStream.Position = 0;
                                await bodyStream.CopyToAsync(targetStream);
                            }

                            bodyStream.Close();
                        }
                        catch (Exception ex)
                        {
                            response = GetResponseMessage(HttpStatusCode.BadRequest, ex.Message);
                            return(response);
                        }
                    }
                    else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                    {
                        var key      = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
                        var encoding = GetEncoding(section);
                        using (var streamReader = new StreamReader(
                                   section.Body,
                                   encoding,
                                   detectEncodingFromByteOrderMarks: true,
                                   bufferSize: 1024,
                                   leaveOpen: true))
                        {
                            // The value length limit is enforced by MultipartBodyLengthLimit
                            var attachmentValue = await streamReader.ReadToEndAsync();

                            if (String.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
                            {
                                value = String.Empty;
                            }
                            formAccumulator.Append(key.ToString(), attachmentValue);

                            if (formAccumulator.ValueCount > _defaultFormOptions.ValueCountLimit)
                            {
                                response = GetResponseMessage(HttpStatusCode.BadRequest, MessageConstant.KeyCountLimit);
                                return(response);
                            }
                        }
                    }
                }

                // Drains any remaining section body that has not been consumed and
                // reads the headers for the next section.
                section = await reader.ReadNextSectionAsync();
            }

            if (formAccumulator.GetResults().Count < 0)
            {
                response = GetResponseMessage(HttpStatusCode.BadRequest, MessageConstant.NoMetaData);
                return(response);
            }
            else if (formAccumulator.GetResults().Count > 1)
            {
                response = GetResponseMessage(HttpStatusCode.BadRequest, MessageConstant.MoreThanOneMetaData);
                return(response);
            }
            else
            {
                var batchMetaDataDictionary = formAccumulator.GetResults().FirstOrDefault();
                if (batchMetaDataDictionary.Key != "batchMetaData")
                {
                    response = GetResponseMessage(HttpStatusCode.BadRequest, MessageConstant.NoMetaData);
                    return(response);
                }
                else
                {
                    try
                    {
                        var settings = new JsonSerializerSettings
                        {
                            NullValueHandling     = NullValueHandling.Ignore,
                            MissingMemberHandling = MissingMemberHandling.Ignore
                        };

                        var captureMetaData = JsonConvert.DeserializeObject <ApiMetaData>(batchMetaDataDictionary.Value, settings);

                        STPBatch batch = new STPBatch()
                        {
                            Destination      = "MyQ",
                            Attachments      = attachmentList,
                            BatchMetaData    = captureMetaData,
                            FolderName       = Guid.NewGuid().ToString(),
                            ReceivedDateTime = DateTime.Now,
                            Status           = "Ready"
                        };


                        var rabbitMqServiceInstance = ServiceProxy.Create <IMQService>(new Uri("fabric:/NextGenCapture_POC/NextGenCapture_RabbitMQService"));

                        await rabbitMqServiceInstance.SendToRabbitMessageQueue(batch);
                    }
                    catch (Exception ex)
                    {
                        response = GetResponseMessage(HttpStatusCode.BadRequest, ex.Message);
                        return(response);
                    }
                }
            }


            return(response);
        }
        public async Task<IActionResult> Upload()
        {
            try
            {
                string fileName = string.Empty;
                var ListFileViewModel = new List<FileViewModel>();
                if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
                {
                    return BadRequest($"Expected a multipart request, but got {Request.ContentType}");
                }

                // Used to accumulate all the form url encoded key value pairs in the 
                // request.
                var formAccumulator = new KeyValueAccumulator();

                var boundary = MultipartRequestHelper.GetBoundary(
                    MediaTypeHeaderValue.Parse(Request.ContentType));
                var reader = new MultipartReader(boundary, HttpContext.Request.Body);

                var section = await reader.ReadNextSectionAsync();
                while (section != null)
                {
                    var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out ContentDispositionHeaderValue contentDisposition);

                    if (hasContentDispositionHeader)
                    {
                        if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                        {

                            var file = section.AsFileSection();
                            fileName = file.FileName;

                            ListFileViewModel.Add(new FileViewModel
                            {
                                FileName = file.FileName,
                                Size = file.Section.Body.Length,
                                Type = file.Section.ContentType
                            });
                            string dir = GetImageDir();
                            Directory.CreateDirectory(dir);
                            var path = $@"{dir}\{fileName}";
                            using (var targetStream = System.IO.File.Create(path))
                            {
                                await section.Body.CopyToAsync(targetStream);

                            }

                            if (file.Section.ContentType.ToLower().Contains("image"))
                                ImageHelper.CorrectRotation(path);
                        }
                        else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                        {
                            // Content-Disposition: form-data; name="key"
                            //
                            // value

                            // Do not limit the key name length here because the 
                            // multipart headers length limit is already in effect.
                            var key = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
                            var encoding = GetEncoding(section);
                            using (var streamReader = new StreamReader(
                                section.Body,
                                encoding,
                                detectEncodingFromByteOrderMarks: true,
                                bufferSize: 1024,
                                leaveOpen: true))
                            {
                                // The value length limit is enforced by MultipartBodyLengthLimit
                                var value = await streamReader.ReadToEndAsync();
                                if (string.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
                                {
                                    value = string.Empty;
                                }
                                formAccumulator.Append(key.Value, value);

                                if (formAccumulator.ValueCount > 70)
                                {
                                    throw new InvalidDataException($"Form key count limit 70 exceeded.");
                                }
                            }
                        }
                    }

                    // Drains any remaining section body that has not been consumed and
                    // reads the headers for the next section.
                    section = await reader.ReadNextSectionAsync();
                }
                // Bind form data to a model
                UploadViewModel model = new UploadViewModel { };
                StringValues values = new StringValues();
                var formValueProvider = new FormValueProvider(
                    BindingSource.Form,
                    new FormCollection(formAccumulator.GetResults()),
                    CultureInfo.CurrentCulture);

                formAccumulator.GetResults().TryGetValue("model", out values);
                if (values.Count > 0)
                {
                    model = values.ToString().JsonDeserialize<UploadViewModel>();
                }

                var bindingSuccessful = await TryUpdateModelAsync(model, prefix: "",
                    valueProvider: formValueProvider);
                if (!bindingSuccessful)
                {
                    if (!ModelState.IsValid)
                    {
                        return BadRequest(ModelState);
                    }
                }
                int i = 0;
                foreach (var file in model.Files)
                {
                    ListFileViewModel[i].InputFileField = file.InputFileField;
                    ListFileViewModel[i].Index = i;
                }
                return Json(new UploadViewModel { Entity = model.Entity, Files = ListFileViewModel });
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Esempio n. 13
0
        public async Task <IActionResult> PostImage(string nihii)
        {
            try
            {
                if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
                {
                    return(BadRequest($"Expected a multipart request, but got {Request.ContentType}"));
                }

                // Used to accumulate all the form url encoded key value pairs in the
                // request.
                var formAccumulator = new KeyValueAccumulator();
                var boundary        = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType), 52000);
                var reader          = new MultipartReader(boundary, HttpContext.Request.Body);
                var section         = await reader.ReadNextSectionAsync();

                while (section != null)
                {
                    ContentDispositionHeaderValue contentDisposition;
                    var hasContentDispositionHeader =
                        ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition);

                    if (hasContentDispositionHeader)
                    {
                        if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                        {
                            using (var targetStream = new MemoryStream())
                            {
                                await section.Body.CopyToAsync(targetStream);

                                var  imageName = contentDisposition.FileName.ToString();
                                bool isImage   = false;
                                foreach (var ext in imageExtensions)
                                {
                                    if (imageName.ToLower().EndsWith(ext))
                                    {
                                        isImage = true;
                                    }
                                }

                                imageName = $"{nihii}/" + imageName;
                                //imageName = isImage ? $"{nihii}/images/" + imageName : $"{nihii}/documents/" + imageName;

                                var photoUriResponse = await _storageService.Post(imageName, targetStream.ToArray());

                                if (!photoUriResponse.Success)
                                {
                                    return(BadRequest(photoUriResponse.Error));
                                }
                                return(Json($"{imageName}.jpg"));
                            }
                        }
                        else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                        {
                            var key = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
                            using (var streamReader = new StreamReader(section.Body, Encoding.UTF8, true, 1024, true))
                            {
                                var value = await streamReader.ReadToEndAsync();

                                if (string.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
                                {
                                    value = string.Empty;
                                }
                                formAccumulator.Append(key.Value, value);
                            }
                        }
                    }
                    section = await reader.ReadNextSectionAsync();
                }

                return(NoContent());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message + " ---" + ex.StackTrace));
            }
        }
Esempio n. 14
0
        public async Task <IActionResult> Post()
        {
            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                return(BadRequest($"Expected a multipart request, but got {Request.ContentType}"));
            }

            // Used to accumulate all the form url encoded key value pairs in the
            // request.
            var    formAccumulator       = new KeyValueAccumulator();
            string targetFilePath        = null;
            string targetFileContentType = null;
            var    boundary = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(Request.ContentType),
                DefaultFormOptions.MultipartBoundaryLengthLimit);
            var reader = new MultipartReader(boundary, HttpContext.Request.Body);

            var section = await reader.ReadNextSectionAsync();

            while (section != null)
            {
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);

                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        targetFilePath        = Path.GetTempFileName();
                        targetFileContentType = section.ContentType;
                        var fileName = GetFileName(section.ContentDisposition);
                        using (var targetStream = new FileStream(fileName, FileMode.Append))
                        {
                            await _storage.StoreAndGetFile(fileName, "talentcontest", targetFileContentType, targetStream);

                            //await section.Body.CopyToAsync(targetStream);

                            _logger.LogInformation($"Copied the uploaded file '{targetFilePath}'");
                        }
                    }
                    else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                    {
                        // Content-Disposition: form-data; name="key"
                        //
                        // value

                        // Do not limit the key name length here because the
                        // multipart headers length limit is already in effect.
                        var key      = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
                        var encoding = GetEncoding(section);
                        using (var streamReader = new StreamReader(
                                   section.Body,
                                   encoding,
                                   detectEncodingFromByteOrderMarks: true,
                                   bufferSize: 1024,
                                   leaveOpen: true))
                        {
                            // The value length limit is enforced by MultipartBodyLengthLimit
                            var value = await streamReader.ReadToEndAsync();

                            if (String.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
                            {
                                value = String.Empty;
                            }
                            formAccumulator.Append(key.ToString(), value);

                            if (formAccumulator.ValueCount > DefaultFormOptions.ValueCountLimit)
                            {
                                throw new InvalidDataException($"Form key count limit {DefaultFormOptions.ValueCountLimit} exceeded.");
                            }
                        }
                    }
                }

                // Drains any remaining section body that has not been consumed and
                // reads the headers for the next section.
                section = await reader.ReadNextSectionAsync();
            }

            // Bind form data to a model
            var entry             = new SubmissionViewModel();
            var formValueProvider = new FormValueProvider(
                BindingSource.Form,
                new FormCollection(formAccumulator.GetResults()),
                CultureInfo.CurrentCulture);

            var bindingSuccessful = await TryUpdateModelAsync(entry, prefix : "",
                                                              valueProvider : formValueProvider);

            if (!bindingSuccessful)
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }
            }

            var uploadedData = new Submission
            {
                FirstName      = entry.FirstName,
                LastName       = entry.LastName,
                Email          = entry.Email,
                ManagerName    = entry.ManagerName,
                LocationId     = entry.LocationId,
                PhoneNumber    = entry.PhoneNumber,
                FileName       = entry.FileName,
                Talent         = entry.Talent,
                ImageConsent   = entry.ImageConsent,
                ContestConsent = entry.ContestConsent,
                EmployeeId     = entry.EmployeeId
            };

            return(Json(uploadedData));
        }
Esempio n. 15
0
        //[ValidateAntiForgeryToken]
        public async Task <IActionResult> Upload()
        {
            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                return(BadRequest($"Expected a multipart request, but got {Request.ContentType}"));
            }

            // Used to accumulate all the form url encoded key value pairs in the
            // request.
            var formAccumulator = new KeyValueAccumulator();

            var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType), DefaultFormOptions.MultipartBoundaryLengthLimit);
            var reader   = new MultipartReader(boundary, HttpContext.Request.Body);

            var links = new List <string>();

            var section = await reader.ReadNextSectionAsync();

            while (section != null)
            {
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);

                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        var url = await _imageUploadService.UploadImage(contentDisposition.FileName.Value, section.Body);

                        links.Add(url);
                    }
                    else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                    {
                        // Content-Disposition: form-data; name="key"
                        //
                        // value

                        // Do not limit the key name length here because the
                        // multipart headers length limit is already in effect.
                        var key      = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
                        var encoding = GetEncoding(section);
                        using (var streamReader = new StreamReader(
                                   section.Body,
                                   encoding,
                                   detectEncodingFromByteOrderMarks: true,
                                   bufferSize: 1024,
                                   leaveOpen: true))
                        {
                            // The value length limit is enforced by MultipartBodyLengthLimit
                            var value = await streamReader.ReadToEndAsync();

                            if (string.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
                            {
                                value = string.Empty;
                            }
                            formAccumulator.Append(key.Value, value);

                            if (formAccumulator.ValueCount > DefaultFormOptions.ValueCountLimit)
                            {
                                throw new InvalidDataException($"Form key count limit {DefaultFormOptions.ValueCountLimit} exceeded.");
                            }
                        }
                    }
                }

                // Drains any remaining section body that has not been consumed and
                // reads the headers for the next section.
                section = await reader.ReadNextSectionAsync();
            }

            return(Ok(links));
        }
Esempio n. 16
0
        public async Task <IActionResult> UploadFileStream()
        {
            string fileNameFinaliy = "";

            try
            {
                if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
                {
                    ModelState.AddModelError("Error", $"The request couldn't be processed (Error -1).");
                    return(BadRequest(ModelState));
                }

                if (!MultipartRequestHelper.ValidateAntiforgeryToken(Request.Headers))
                {
                    ModelState.AddModelError("Error", $"The request couldn't be processed (Error 0).");
                    return(BadRequest(ModelState));
                }

                var formAccumulator           = new KeyValueAccumulator();
                var trustedFileNameForDisplay = string.Empty;
                var streamedFileContent       = new HugeMemoryStream();

                var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType), _defaultFormOptions.MultipartBoundaryLengthLimit);
                var reader   = new MultipartReader(boundary, HttpContext.Request.Body);

                var section = await reader.ReadNextSectionAsync();

                if (section == null)
                {
                    ModelState.AddModelError("Error", $"The request couldn't be processed (Error 1).");
                    return(BadRequest(ModelState));
                }

                while (section != null)
                {
                    var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);

                    if (hasContentDispositionHeader)
                    {
                        if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                        {
                            trustedFileNameForDisplay = WebUtility.HtmlEncode(contentDisposition.FileName.Value);
                            streamedFileContent       = await FileHelpers.ProcessStreamedFile(section, contentDisposition, ModelState, _permittedExtensions, _fileSizeLimit);

                            if (!ModelState.IsValid)
                            {
                                return(BadRequest(ModelState));
                            }
                        }
                        else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                        {
                            var key      = HeaderUtilities.RemoveQuotes(contentDisposition.Name).Value;
                            var encoding = GetEncoding(section);

                            if (encoding == null)
                            {
                                ModelState.AddModelError("Error", $"The request couldn't be processed (Error 2).");
                                return(BadRequest(ModelState));
                            }

                            using (var streamReader = new StreamReader(
                                       section.Body,
                                       encoding,
                                       detectEncodingFromByteOrderMarks: true,
                                       bufferSize: 1024,
                                       leaveOpen: true))
                            {
                                var value = await streamReader.ReadToEndAsync();

                                if (string.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
                                {
                                    value = string.Empty;
                                }

                                formAccumulator.Append(key, value);

                                if (formAccumulator.ValueCount > _defaultFormOptions.ValueCountLimit)
                                {
                                    ModelState.AddModelError("Error", $"The request couldn't be processed (Error 3).");

                                    return(BadRequest(ModelState));
                                }
                            }
                        }
                    }

                    if (!ModelState.IsValid)
                    {
                        return(BadRequest(ModelState));
                    }

                    section = await reader.ReadNextSectionAsync();
                }

                // Bind form data to the model
                var formData          = new FormData();
                var formValueProvider = new FormValueProvider(BindingSource.Form, new FormCollection(formAccumulator.GetResults()), CultureInfo.CurrentCulture);
                var bindingSuccessful = await TryUpdateModelAsync(formData, prefix : "", valueProvider : formValueProvider);

                if (!bindingSuccessful)
                {
                    ModelState.AddModelError("Error", "The request couldn't be processed (Error 5).");
                    return(BadRequest(ModelState));
                }

                if (string.IsNullOrEmpty(trustedFileNameForDisplay) || streamedFileContent.Length <= 0)
                {
                    ModelState.AddModelError("Error", "The request couldn't be processed (Error 6).");
                    return(BadRequest(ModelState));
                }

                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                string trustedFileNameForFileStorage = Path.GetRandomFileName();
                fileNameFinaliy = Path.Combine(_targetFilePath, trustedFileNameForFileStorage);
                string mimeType = FindMimeHelpers.GetMimeFromStream(streamedFileContent);

                using (var targetStream = System.IO.File.Create(fileNameFinaliy))
                {
                    streamedFileContent.CopyTo(targetStream);
                    _logger.LogInformation($"Uploaded file '{trustedFileNameForDisplay}' saved to '{_targetFilePath}' as {trustedFileNameForFileStorage}");
                }

                var model = await SaveInDb(HttpContext.Request.HttpContext.Connection.RemoteIpAddress.ToString(), fileNameFinaliy, trustedFileNameForDisplay, trustedFileNameForFileStorage, streamedFileContent.Length, mimeType);

                return(new OkObjectResult(model.Hash.Trim().ToLower()));
            }
            catch (Exception ex)
            {
                if (!string.IsNullOrEmpty(fileNameFinaliy) && System.IO.File.Exists(fileNameFinaliy))
                {
                    System.IO.File.Delete(fileNameFinaliy);
                }

                ModelState.AddModelError("Error", ex.Message);

                if (ex.InnerException != null)
                {
                    ModelState.AddModelError("InnerException", ex.InnerException.Message);
                }

                return(BadRequest(ModelState));
            }
        }
        public async Task <IActionResult> UploadDatabase()
        {
            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                ModelState.AddModelError("File",
                                         $"The request couldn't be processed (Error 1).");
                // Log error

                return(BadRequest(ModelState));
            }

            // Accumulate the form data key-value pairs in the request (formAccumulator).
            var formAccumulator             = new KeyValueAccumulator();
            var trustedFileNameForDisplay   = string.Empty;
            var untrustedFileNameForStorage = string.Empty;
            var streamedFileContent         = new byte[0];

            var boundary = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(Request.ContentType),
                _defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader = new MultipartReader(boundary, HttpContext.Request.Body);

            var section = await reader.ReadNextSectionAsync();

            while (section != null)
            {
                var hasContentDispositionHeader =
                    ContentDispositionHeaderValue.TryParse(
                        section.ContentDisposition, out var contentDisposition);

                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper
                        .HasFileContentDisposition(contentDisposition))
                    {
                        untrustedFileNameForStorage = contentDisposition.FileName.Value;
                        // Don't trust the file name sent by the client. To display
                        // the file name, HTML-encode the value.
                        trustedFileNameForDisplay = WebUtility.HtmlEncode(
                            contentDisposition.FileName.Value);

                        streamedFileContent =
                            await FileHelpers.ProcessStreamedFile(section, contentDisposition,
                                                                  ModelState, _permittedExtensions, _fileSizeLimit);

                        if (!ModelState.IsValid)
                        {
                            return(BadRequest(ModelState));
                        }
                    }
                    else if (MultipartRequestHelper
                             .HasFormDataContentDisposition(contentDisposition))
                    {
                        // Don't limit the key name length because the
                        // multipart headers length limit is already in effect.
                        var key = HeaderUtilities
                                  .RemoveQuotes(contentDisposition.Name).Value;
                        var encoding = GetEncoding(section);

                        if (encoding == null)
                        {
                            ModelState.AddModelError("File",
                                                     $"The request couldn't be processed (Error 2).");
                            // Log error

                            return(BadRequest(ModelState));
                        }

                        using (var streamReader = new StreamReader(
                                   section.Body,
                                   encoding,
                                   detectEncodingFromByteOrderMarks: true,
                                   bufferSize: 1024,
                                   leaveOpen: true))
                        {
                            // The value length limit is enforced by
                            // MultipartBodyLengthLimit
                            var value = await streamReader.ReadToEndAsync();

                            if (string.Equals(value, "undefined",
                                              StringComparison.OrdinalIgnoreCase))
                            {
                                value = string.Empty;
                            }

                            formAccumulator.Append(key, value);

                            if (formAccumulator.ValueCount >
                                _defaultFormOptions.ValueCountLimit)
                            {
                                // Form key count limit of
                                // _defaultFormOptions.ValueCountLimit
                                // is exceeded.
                                ModelState.AddModelError("File",
                                                         $"The request couldn't be processed (Error 3).");
                                // Log error

                                return(BadRequest(ModelState));
                            }
                        }
                    }
                }

                // Drain any remaining section body that hasn't been consumed and
                // read the headers for the next section.
                section = await reader.ReadNextSectionAsync();
            }

            // Bind form data to the model
            var formData          = new FormData();
            var formValueProvider = new FormValueProvider(
                BindingSource.Form,
                new FormCollection(formAccumulator.GetResults()),
                CultureInfo.CurrentCulture);
            var bindingSuccessful = await TryUpdateModelAsync(formData, prefix : "",
                                                              valueProvider : formValueProvider);

            if (!bindingSuccessful)
            {
                ModelState.AddModelError("File",
                                         "The request couldn't be processed (Error 5).");
                // Log error

                return(BadRequest(ModelState));
            }

            // **WARNING!**
            // In the following example, the file is saved without
            // scanning the file's contents. In most production
            // scenarios, an anti-virus/anti-malware scanner API
            // is used on the file before making the file available
            // for download or for use by other systems.
            // For more information, see the topic that accompanies
            // this sample app.

            var file = new AppFile()
            {
                Content       = streamedFileContent,
                UntrustedName = untrustedFileNameForStorage,
                Note          = formData.Note,
                Size          = streamedFileContent.Length,
                UploadDT      = DateTime.UtcNow
            };

            _context.File.Add(file);
            await _context.SaveChangesAsync();

            return(Created(nameof(StreamingController), null));
        }
Esempio n. 18
0
        /// <summary>
        /// 这个特性能让这个页面带上验证信息,令牌
        ///
        /// </summary>
        /// <returns></returns>
        //[HttpGet]
        //[GenerateAntiforgeryTokenCookieForAjax]
        //public IActionResult Index()
        //{
        //    return View();
        //}



        #region --上传方法, 不自动绑定,可上传大文件--
        /// <summary>
        /// 上传方法
        /// </summary>
        /// <returns></returns>
        // 1. Disable the form value model binding here to take control of handling
        //    potentially large files.
        //    禁止了表单到模型自动绑定,以便能控制好大文件
        // 2. Typically antiforgery tokens are sent in request body, but since we
        //    do not want to read the request body early, the tokens are made to be
        //    sent via headers. The antiforgery token filter first looks for tokens
        //    in the request header and then falls back to reading the body.
        //[HttpPost]
        //[DisableFormValueModelBinding]//不进行表单到模型的绑定
        //[ValidateAntiForgeryToken]//检查令牌
        protected async Task <IActionResult> Upload(Func <IDictionary <string, StringValues>, string> filePathFunc)
        {
            // 检查是否多部分数据类型
            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                return(BadRequest($"Expected a multipart request, but got {Request.ContentType}"));
            }

            // Used to accumulate all the form url encoded key value pairs in the request.
            var    formAccumulator = new KeyValueAccumulator();
            string targetFilePath  = null; //目标文件路经
            //这里应该是获取http提交的分段信息
            var boundary = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(Request.ContentType),
                _defaultFormOptions.MultipartBoundaryLengthLimit);
            // 创建一个读取器
            var reader = new MultipartReader(boundary, HttpContext.Request.Body);
            // 异步读取下一个部件
            var section = await reader.ReadNextSectionAsync();

            // 循环检查读取的部件是否为空
            while (section != null)
            {
                ContentDispositionHeaderValue contentDisposition;
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition);
                // 是否有内容配置头值
                if (hasContentDispositionHeader)
                {
                    // 是否文件内容配置
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        // 一个临时文件名
                        section.Headers.Keys.Foreach(key => {
                            LogInfo($"{key}:{section.Headers[key]}");
                        });
                        var file_ex = section.ContentDisposition.LastIndexOfRight(".").RemoveFileNameIllegalChar();
                        targetFilePath = Constant.CurrDir + "temp" + DateTime.Now.DataStr("") + "." + file_ex;//Path.GetTempFileName();
                        targetFilePath = filePathFunc(section.Headers);
                        // 写入文件到临时文件
                        using (var targetStream = System.IO.File.Create(targetFilePath))
                        {
                            // 此方法接收数据不全
                            await section.Body.CopyToAsync(targetStream);

                            //LogInfo($"Copied the uploaded file '{targetFilePath}'");
                        }
                    }
                    // 是否有表单,这一段用于处理所有键值对
                    else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                    {
                        // Content-Disposition: form-data; name="key" value
                        // Do not limit the key name length here because the
                        // multipart headers length limit is already in effect.
                        var key      = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
                        var encoding = GetEncoding(section);
                        using (var streamReader = new StreamReader(
                                   section.Body,
                                   encoding,
                                   detectEncodingFromByteOrderMarks: true,
                                   bufferSize: 5120000,
                                   leaveOpen: true))
                        {
                            // The value length limit is enforced by MultipartBodyLengthLimit
                            // 值长度被MultipartBodyLengthLimit强制限制了
                            var value = await streamReader.ReadToEndAsync();//读取流

                            if (String.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
                            {
                                value = String.Empty;
                            }
                            formAccumulator.Append(key.ToString(), value);
                            LogInfo($"key={key.ToString()} | {value}");

                            if (formAccumulator.ValueCount > _defaultFormOptions.ValueCountLimit)
                            {
                                throw new InvalidDataException($"Form key count limit {_defaultFormOptions.ValueCountLimit} exceeded.");
                            }
                        }
                    }
                }

                // Drains any remaining section body that has not been consumed and
                // reads the headers for the next section.
                // 读取下一个节点头(部分)
                section = await reader.ReadNextSectionAsync();
            }


            //这里绑定表单数据到
            // Bind form data to a model
            //var user = new User();
            //var formValueProvider = new FormValueProvider(
            //    BindingSource.Form,
            //    new FormCollection(formAccumulator.GetResults()),
            //    CultureInfo.CurrentCulture);

            //var bindingSuccessful = await TryUpdateModelAsync(user, prefix: "",
            //    valueProvider: formValueProvider);
            //if (!bindingSuccessful)
            //{
            //    if (!ModelState.IsValid)
            //    {
            //        return BadRequest(ModelState);
            //    }
            //}

            //var uploadedData = new UploadedData()
            //{
            //    Name = user.Name,
            //    Age = user.Age,
            //    Zipcode = user.Zipcode,
            //    FilePath = targetFilePath
            //};
            return(Json("success"));
        }
Esempio n. 19
0
        public async Task <IActionResult> Upload()
        {
            // Used to accumulate all the form url encoded key value pairs in the
            // request.
            var    formAccumulator = new KeyValueAccumulator();
            string targetFilePath  = null;

            var boundary = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(Request.ContentType),
                StreamingController._defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader = new MultipartReader(boundary, HttpContext.Request.Body);

            var section = await reader.ReadNextSectionAsync();

            while (section != null)
            {
                ContentDispositionHeaderValue contentDisposition;
                var hasContentDispositionHeader =
                    ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition);

                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        targetFilePath = Path.GetTempFileName();
                        using (var targetStream = System.IO.File.Create(targetFilePath))
                        {
                            await section.Body.CopyToAsync(targetStream);

                            this.logger.LogInformation($"Copied the uploaded file '{targetFilePath}'");
                        }
                    }
                    else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                    {
                        // Content-Disposition: form-data; name="key"
                        //
                        // value

                        // Do not limit the key name length here because the
                        // multipart headers length limit is already in effect.
                        var key      = HeaderUtilities.RemoveQuotes(contentDisposition.Name).Value;
                        var encoding = StreamingController.GetEncoding(section);
                        using (var streamReader = new StreamReader(
                                   section.Body,
                                   encoding,
                                   detectEncodingFromByteOrderMarks: true,
                                   bufferSize: 1024,
                                   leaveOpen: true))
                        {
                            // The value length limit is enforced by MultipartBodyLengthLimit
                            var value = await streamReader.ReadToEndAsync();

                            if (String.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
                            {
                                value = String.Empty;
                            }

                            formAccumulator.Append(key, value);

                            if (formAccumulator.ValueCount > StreamingController._defaultFormOptions.ValueCountLimit)
                            {
                                throw new InvalidDataException(
                                          $"Form key count limit {StreamingController._defaultFormOptions.ValueCountLimit} exceeded.");
                            }
                        }
                    }
                }

                // Drains any remaining section body that has not been consumed and
                // reads the headers for the next section.
                section = await reader.ReadNextSectionAsync();
            }

            await this.importer.ImportDataFromCSV(targetFilePath);

            return(Ok());
        }
Esempio n. 20
0
        private async Task <(MemberDto, ImageDto?)> UploadUserImageMultipartContent(Guid targetUserId, Stream requestBody, byte[] rowVersion, string?contentType, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var now = _systemClock.UtcNow.UtcDateTime;

            var defaultFormOptions = new FormOptions();
            // Create a Collection of KeyValue Pairs.
            var formAccumulator = new KeyValueAccumulator();
            // Determine the Multipart Boundary.
            var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(contentType), defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader   = new MultipartReader(boundary, requestBody);
            var section  = await reader.ReadNextSectionAsync(cancellationToken);

            ImageDto? imageDto = null;
            MemberDto userDto  = new MemberDto();

            // Loop through each 'Section', starting with the current 'Section'.
            while (section != null)
            {
                // Check if the current 'Section' has a ContentDispositionHeader.
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);
                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        if (contentDisposition != null)
                        {
                            var sectionFileName = contentDisposition.FileName.Value;
                            // use an encoded filename in case there is anything weird
                            var encodedFileName = WebUtility.HtmlEncode(Path.GetFileName(sectionFileName));

                            // read the section filename to get the content type
                            var fileExtension = Path.GetExtension(sectionFileName);

                            // now make it unique
                            var uniqueFileName = $"{Guid.NewGuid()}{fileExtension}";

                            if (!_acceptedFileTypes.Contains(fileExtension.ToLower()))
                            {
                                _logger.LogError("file extension:{0} is not an accepted image file", fileExtension);
                                throw new ValidationException("Image", "The image is not in an accepted format");
                            }

                            var compressedImage = _imageService.TransformImageForAvatar(section.Body);

                            try
                            {
                                await _blobStorageProvider.UploadFileAsync(compressedImage.Image, uniqueFileName,
                                                                           MimeTypesMap.GetMimeType(encodedFileName), cancellationToken);
                            }
                            catch (Exception ex)
                            {
                                _logger.LogError(ex, "An error occurred uploading file to blob storage");
                                throw;
                            }

                            // trick to get the size without reading the stream in memory
                            var size = section.Body.Position;

                            imageDto = new ImageDto
                            {
                                FileSizeBytes = size,
                                FileName      = uniqueFileName,
                                Height        = compressedImage.Height,
                                Width         = compressedImage.Width,
                                IsDeleted     = false,
                                MediaType     = compressedImage.MediaType,
                                CreatedBy     = targetUserId,
                                CreatedAtUtc  = now
                            };

                            var imageValidator        = new ImageValidator(MaxFileSizeBytes);
                            var imageValidationResult = await imageValidator.ValidateAsync(imageDto, cancellationToken);

                            if (imageValidationResult.Errors.Count > 0)
                            {
                                await _blobStorageProvider.DeleteFileAsync(uniqueFileName);

                                _logger.LogError("File size:{0} is greater than the max allowed size:{1}", size, MaxFileSizeBytes);
                                throw new ValidationException(imageValidationResult);
                            }
                        }
                    }
                    else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                    {
                        // if for some reason other form data is sent it would get processed here
                        var key = HeaderUtilities.RemoveQuotes(contentDisposition?.Name.ToString().ToLowerInvariant());

                        var encoding = GetEncoding(section);
                        using (var streamReader = new StreamReader(section.Body, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true))
                        {
                            var value = await streamReader.ReadToEndAsync();

                            if (string.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
                            {
                                value = string.Empty;
                            }
                            formAccumulator.Append(key.Value, value);
                            if (formAccumulator.ValueCount > defaultFormOptions.ValueCountLimit)
                            {
                                _logger.LogError("UserEdit: Form key count limit {0} exceeded.", defaultFormOptions.ValueCountLimit);
                                throw new FormatException($"Form key count limit { defaultFormOptions.ValueCountLimit } exceeded.");
                            }
                        }
                    }
                }
                // Begin reading the next 'Section' inside the 'Body' of the Request.
                section = await reader.ReadNextSectionAsync(cancellationToken);
            }

            if (formAccumulator.HasValues)
            {
                var formValues = formAccumulator.GetResults();

                // Check if users been updated
                // Unable to place in controller due to disabling form value model binding
                var user = await _userCommand.GetMemberAsync(targetUserId, cancellationToken);

                if (!user.RowVersion.SequenceEqual(rowVersion))
                {
                    _logger.LogError($"Precondition Failed: UpdateUserAsync - User:{0} has changed prior to submission", targetUserId);
                    throw new PreconditionFailedExeption("Precondition Failed: User has changed prior to submission");
                }

                var firstNameFound = formValues.TryGetValue("firstName", out var firstName);
                if (firstNameFound is false || string.IsNullOrEmpty(firstName))
                {
                    throw new ArgumentNullException($"First name was not provided");
                }
                formValues.TryGetValue("lastName", out var surname);

                var pronoundsFound = formValues.TryGetValue("pronouns", out var pronouns);
                if (pronoundsFound is false)
                {
                    throw new ArgumentNullException($"Pronouns were not provided");
                }

                formValues.TryGetValue("imageid", out var image);

                var imageId = Guid.TryParse(image, out var imageGuid) ? (Guid?)imageGuid : null;
                if (imageId.HasValue)
                {
                    if (imageId == new Guid())
                    {
                        throw new ArgumentOutOfRangeException($"Incorrect Id provided");
                    }
                }

                userDto = new MemberDto
                {
                    Id            = targetUserId,
                    FirstName     = firstName,
                    Surname       = surname,
                    Pronouns      = pronouns,
                    ImageId       = imageId,
                    ModifiedAtUTC = now,
                    ModifiedBy    = targetUserId,
                };
            }

            return(userDto, imageDto);
        }
Esempio n. 21
0
        public async Task PostImportAsync()
        {
            using (ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
            {
                if (HttpContext.Request.HasFormContentType == false)
                {
                    HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; // Bad request
                    using (var writer = new BlittableJsonTextWriter(context, ResponseBodyStream()))
                    {
                        context.Write(writer, new DynamicJsonValue
                        {
                            ["Type"]  = "Error",
                            ["Error"] = "This endpoint requires form content type"
                        });
                        return;
                    }
                }

                var operationId = GetLongQueryString("operationId");
                var token       = CreateOperationToken();

                var result = new SmugglerResult();
                await Database.Operations.AddOperation(Database, "Import to: " + Database.Name,
                                                       Operations.OperationType.DatabaseImport,
                                                       onProgress =>
                {
                    return(Task.Run(async() =>
                    {
                        try
                        {
                            var boundary = MultipartRequestHelper.GetBoundary(
                                MediaTypeHeaderValue.Parse(HttpContext.Request.ContentType),
                                MultipartRequestHelper.MultipartBoundaryLengthLimit);
                            var reader = new MultipartReader(boundary, HttpContext.Request.Body);
                            DatabaseSmugglerOptionsServerSide options = null;

                            while (true)
                            {
                                var section = await reader.ReadNextSectionAsync().ConfigureAwait(false);
                                if (section == null)
                                {
                                    break;
                                }

                                if (ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out ContentDispositionHeaderValue contentDisposition) == false)
                                {
                                    continue;
                                }

                                if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                                {
                                    var key = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
                                    if (key != "importOptions")
                                    {
                                        continue;
                                    }

                                    BlittableJsonReaderObject blittableJson;
                                    if (section.Headers.ContainsKey("Content-Encoding") && section.Headers["Content-Encoding"] == "gzip")
                                    {
                                        using (var gzipStream = new GZipStream(section.Body, CompressionMode.Decompress))
                                        {
                                            blittableJson = await context.ReadForMemoryAsync(gzipStream, "importOptions");
                                        }
                                    }
                                    else
                                    {
                                        blittableJson = await context.ReadForMemoryAsync(section.Body, "importOptions");
                                    }

                                    options = JsonDeserializationServer.DatabaseSmugglerOptions(blittableJson);
                                    continue;
                                }

                                if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition) == false)
                                {
                                    continue;
                                }

                                var stream = new GZipStream(section.Body, CompressionMode.Decompress);
                                DoImportInternal(context, stream, options, result, onProgress, token);
                            }
                        }
                        catch (Exception e)
                        {
                            result.AddError($"Error occurred during export. Exception: {e.Message}");
                            throw;
                        }

                        return (IOperationResult)result;
                    }));
                }, operationId, token).ConfigureAwait(false);

                WriteImportResult(context, result, ResponseBodyStream());
            }
        public async Task <IActionResult> Upload()
        {
            try
            {
                if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
                {
                    return(BadRequest($"Expected a multipart request, but got {Request.ContentType}"));
                }

                // Used to accumulate all the form url encoded key value pairs in the request.
                var    formAccumulator = new KeyValueAccumulator();
                string targetFilePath  = null;

                var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType), DefaultFormOptions.MultipartBoundaryLengthLimit);
                var reader   = new MultipartReader(boundary, HttpContext.Request.Body);

                var section = await reader.ReadNextSectionAsync();

                while (section != null)
                {
                    var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);
                    if (hasContentDispositionHeader)
                    {
                        if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                        {
                            targetFilePath = Path.GetTempFileName();
                            using (var targetStream = System.IO.File.Create(targetFilePath))
                            {
                                await section.Body.CopyToAsync(targetStream);

                                _logger.LogInformation($"Copied the uploaded file '{targetFilePath}'");
                            }
                        }
                        else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                        {
                            // Do not limit the key name length here because the
                            // multipart headers length limit is already in effect.
                            var key      = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
                            var encoding = GetEncoding(section);
                            using (var streamReader = new StreamReader(section.Body, encoding, true, 1024, true))
                            {
                                // The value length limit is enforced by MultipartBodyLengthLimit
                                var value = await streamReader.ReadToEndAsync();

                                if (string.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
                                {
                                    value = string.Empty;
                                }
                                formAccumulator.Append(key.ToString(), value);

                                if (formAccumulator.ValueCount > DefaultFormOptions.ValueCountLimit)
                                {
                                    throw new InvalidDataException($"Form key count limit {DefaultFormOptions.ValueCountLimit} exceeded.");
                                }
                            }
                        }
                    }

                    // Drains any remaining section body that has not been consumed and reads the headers for the next section.
                    section = await reader.ReadNextSectionAsync();
                }

                if (string.IsNullOrEmpty(targetFilePath) || !System.IO.File.Exists(targetFilePath))
                {
                    _logger.LogError("File not created!");
                    return(StatusCode(500, "Internal server error"));
                }

                // Import the file
                Stopwatch sw = new Stopwatch();
                sw.Start();
                await _fileImport.ImportAsync(targetFilePath);

                sw.Stop();
                TimeSpan ts = sw.Elapsed;
                _logger.LogInformation(string.Format("Import run time: {0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10));

                return(Ok(true));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return(StatusCode(500, "Internal server error"));
            }
        }
        private async Task <KeyValueAccumulator> SaveStream(MultipartReader reader, string targetFilePath)
        {
            MultipartSection section = await reader.ReadNextSectionAsync();

            var formAccumulator = new KeyValueAccumulator();

            while (section != null)
            {
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);

                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        using (var targetStream = System.IO.File.Create(targetFilePath))
                        {
                            await section.Body.CopyToAsync(targetStream);

                            Logger.LogInformation($"Copied the uploaded file '{targetFilePath}'");
                        }
                    }
                    else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                    {
                        // Content-Disposition: form-data; name="key"
                        // value

                        // Do not limit the key name length here because the
                        // multipart headers length limit is already in effect.
                        var key      = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
                        var encoding = GetEncoding(section);
                        using (var streamReader = new StreamReader(
                                   section.Body,
                                   encoding,
                                   detectEncodingFromByteOrderMarks: true,
                                   bufferSize: 1024,
                                   leaveOpen: true))
                        {
                            // The value length limit is enforced by MultipartBodyLengthLimit
                            var value = await streamReader.ReadToEndAsync();

                            if (string.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
                            {
                                value = string.Empty;
                            }
                            formAccumulator.Append(key.Value, value);

                            if (formAccumulator.ValueCount > DefaultFormOptions.ValueCountLimit)
                            {
                                throw new InvalidDataException($"Form key count limit {DefaultFormOptions.ValueCountLimit} exceeded.");
                            }
                        }
                    }
                }

                // Drains any remaining section body that has not been consumed and
                // reads the headers for the next section.
                section = await reader.ReadNextSectionAsync();
            }

            return(formAccumulator);
        }
Esempio n. 24
0
        /// <summary>
        /// Handle multi-part form data file streams.
        /// </summary>
        public static async Task <string> StreamFile(this HttpRequest request, string filename, ILogger log)
        {
            var    formAccumulator    = new KeyValueAccumulator();
            string targetFilePath     = null;
            var    defaultFormOptions = new FormOptions();

            // Boundary is required by the MultipartReader, but we'll auto generate one in the helper, it
            // doesn't need to be provided in the request header.
            var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(request.ContentType), defaultFormOptions.MultipartBoundaryLengthLimit);

            var reader  = new MultipartReader(boundary, request.Body);
            var section = await reader.ReadNextSectionAsync();

            log.LogDebug("Processing file stream...");

            while (section != null)
            {
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);
                var dispositionParameters       = contentDisposition.Parameters.Aggregate("", (current, parameter) => $"{current},{parameter}");
                log.LogDebug($"Processing section '{contentDisposition.DispositionType}:{dispositionParameters}'");

                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        targetFilePath = Path.Combine(Path.GetTempPath(), filename);
                        log.LogDebug($"Writing stream to '{targetFilePath}'");

                        using (var targetStream = File.Create(targetFilePath))
                        {
                            await section.Body.CopyToAsync(targetStream);
                        }
                    }
                    else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                    {
                        // Do not limit the key name length here because the multipart headers length limit is already in effect.
                        var key      = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
                        var encoding = section.GetEncoding();

                        using (var streamReader = new StreamReader(
                                   section.Body,
                                   encoding,
                                   detectEncodingFromByteOrderMarks: true,
                                   bufferSize: 1024,
                                   leaveOpen: true))
                        {
                            // The value length limit is enforced by MultipartBodyLengthLimit
                            var value = await streamReader.ReadToEndAsync();

                            if (string.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
                            {
                                value = string.Empty;
                            }

                            formAccumulator.Append(key.ToString(), value);

                            if (formAccumulator.ValueCount > defaultFormOptions.ValueCountLimit)
                            {
                                throw new InvalidDataException($"Form key count limit {defaultFormOptions.ValueCountLimit} exceeded.");
                            }
                        }
                    }
                }

                // Drains any remaining section body that has not been consumed and reads the headers for the next section.
                section = await reader.ReadNextSectionAsync();
            }

            log.LogDebug("Completed processing request body.");

            return(targetFilePath);
        }
Esempio n. 25
0
        public async Task <IActionResult> upload()
        {
            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                return(BadRequest($"Expected a multipart request, but got {Request.ContentType}"));
            }

            StringValues UserName;

            SiteConfig.HttpContextAccessor.HttpContext.Request.Headers.TryGetValue("UName", out UserName);

            // Used to accumulate all the form url encoded key value pairs in the
            // request.
            var formAccumulator = new KeyValueAccumulator();
            // string targetFilePath = null;

            var boundary = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(Request.ContentType),
                _defaultFormOptions.MultipartBoundaryLengthLimit);

            var reader = new MultipartReader(boundary, HttpContext.Request.Body);

            var section = await reader.ReadNextSectionAsync();

            var uploadPath = SiteConfig.Environment.ContentRootPath + "/wwwroot/uploads/source/";

            var fileName = "";

            while (section != null)
            {
                ContentDispositionHeaderValue contentDisposition;
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition,
                                                                                         out contentDisposition);

                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        var output = formAccumulator.GetResults();
                        var chunk  = "0";
                        foreach (var item in output)
                        {
                            if (item.Key == "name")
                            {
                                fileName = item.Value;
                            }
                            else if (item.Key == "chunk")
                            {
                                chunk = item.Value;
                            }
                        }

                        var Path = uploadPath + "" + fileName;
                        using (var fs = new FileStream(Path, chunk == "0" ? FileMode.Create : FileMode.Append))
                        {
                            await section.Body.CopyToAsync(fs);

                            fs.Flush();
                        }
                    }
                    else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                    {
                        var key      = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
                        var encoding = GetEncoding(section);
                        using (var streamReader = new StreamReader(
                                   section.Body,
                                   encoding,
                                   detectEncodingFromByteOrderMarks: true,
                                   bufferSize: 1024,
                                   leaveOpen: true))
                        {
                            // The value length limit is enforced by MultipartBodyLengthLimit
                            var value = await streamReader.ReadToEndAsync();

                            if (String.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
                            {
                                value = String.Empty;
                            }
                            formAccumulator.Append(key.ToString(), value);

                            if (formAccumulator.ValueCount > _defaultFormOptions.ValueCountLimit)
                            {
                                throw new InvalidDataException($"Form key count limit {_defaultFormOptions.ValueCountLimit} exceeded.");
                            }
                        }
                    }
                }

                var result = formAccumulator.GetResults();

                // Drains any remaining section body that has not been consumed and
                // reads the headers for the next section.
                section = await reader.ReadNextSectionAsync();
            }


            string url       = "/uploads/source/" + fileName;
            string fileType  = System.IO.Path.GetExtension(fileName);
            string fileIndex = fileName.Replace(fileType, "");

            return(Ok(new { jsonrpc = "2.0", result = "OK", fname = fileName, url = url, filetype = fileType, filename = fileName, fileIndex = fileIndex }));
        }
        public async Task <FormDataUploadAccumulator> UploadFormAsync(MultipartReader reader)
        {
            try
            {
                var section = await reader.ReadNextSectionAsync();

                var filename        = Guid.NewGuid().ToString();
                var formAccumulator = new KeyValueAccumulator();
                using (var destinationStream = await _context.GetBucket().OpenUploadStreamAsync(filename))
                {
                    var id = destinationStream.Id; // the unique Id of the file being uploaded

                    while (section != null)
                    {
                        var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out ContentDispositionHeaderValue contentDisposition);

                        if (hasContentDispositionHeader)
                        {
                            if (_requestHelper.HasFileContentDisposition(contentDisposition))
                            {
                                filename = HeaderUtilities.RemoveQuotes(contentDisposition.FileName).ToString();
                                // write the contents of the file to stream using asynchronous Stream methods
                                await section.Body.CopyToAsync(destinationStream);
                            }
                            else if (_requestHelper.HasFormDataContentDisposition(contentDisposition))
                            {
                                // Content-Disposition: form-data; name="key"
                                //
                                // value

                                // Do not limit the key name length here because the
                                // multipart headers length limit is already in effect.
                                var key      = HeaderUtilities.RemoveQuotes(contentDisposition.Name).ToString();
                                var encoding = _requestHelper.GetEncoding(section);
                                using (var streamReader = new StreamReader(section.Body, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true))
                                {
                                    // The value length limit is enforced by MultipartBodyLengthLimit
                                    var value = await streamReader.ReadToEndAsync();

                                    if (String.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
                                    {
                                        value = String.Empty;
                                    }
                                    formAccumulator.Append(key, value);

                                    //if (formAccumulator.ValueCount > 4)//Todo get default value
                                    //{
                                    //    throw new InvalidDataException($"Form key count limit exceeded.");
                                    //}
                                }
                            }
                        }

                        // Drains any remaining section body that has not been consumed and
                        // reads the headers for the next section.
                        section = await reader.ReadNextSectionAsync();
                    }

                    await destinationStream.CloseAsync(); // optional but recommended so Dispose does not block

                    var extension = Path.GetExtension(filename);
                    var newName   = Guid.NewGuid().ToString() + extension;
                    _context.GetBucket().Rename(id, newName);
                    return(new FormDataUploadAccumulator
                    {
                        FileId = id.ToString(),
                        Filename = newName,
                        Accumulator = formAccumulator
                    });
                }
            }
            catch (Exception ex)
            {
                // log or manage the exception
                throw ex;
            }
        }
        public async Task <IActionResult> RecieveFile()
        {
            Instance instance = null;

            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                return(BadRequest($"Expected a multipart request, but got {Request.ContentType}"));
            }

            //var formAccumulator = new KeyValueAccumulator();
            string targetFilePath = null;

            var boundary = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(Request.ContentType),
                _defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader = new MultipartReader(boundary, HttpContext.Request.Body);

            var section = await reader.ReadNextSectionAsync();

            while (section != null)
            {
                ContentDispositionHeaderValue contentDisposition;
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition);

                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        targetFilePath = this._pathFinder.GetStoragePathForLinkRecieve(instance);
                        using (var targetStream = System.IO.File.Create(targetFilePath))
                        {
                            await section.Body.CopyToAsync(targetStream);

                            _logger.LogInformation($"Copied the uploaded file '{targetFilePath}'");
                        }
                    }
                    else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                    {
                        // Content-Disposition: form-data; name="key"
                        // value
                        // Do not limit the key name length here because the
                        // multipart headers length limit is already in effect.
                        var key      = HeaderUtilities.RemoveQuotes(contentDisposition.Name).Value;
                        var encoding = GetEncoding(section);
                        using (var streamReader = new StreamReader(
                                   section.Body,
                                   encoding,
                                   detectEncodingFromByteOrderMarks: true,
                                   bufferSize: 1024,
                                   leaveOpen: true))
                        {
                            // The value length limit is enforced by MultipartBodyLengthLimit
                            var value = await streamReader.ReadToEndAsync();

                            if (String.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
                            {
                                value = String.Empty;
                            }
                            if (key.Equals("instance") && !string.IsNullOrEmpty(value))
                            {
                                instance = JsonConvert.DeserializeObject <Instance>(value);
                            }
                        }
                    }
                }
                section = await reader.ReadNextSectionAsync();
            }

            var dAttrs = this._dicomParser.Extract(instance, _pathFinder);

            this._storageRepository.AddNewStudy(dAttrs, true).GetAwaiter().GetResult();
            return(Ok(new { count = 1 }));
        }
Esempio n. 28
0
        public async Task <IActionResult> StreamingUpload(Int32 id)
        {
            Debug.WriteLine("In Streaming Upload for Trip Number: " + id);

            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                return(BadRequest($"Expected a multipart request, but got {Request.ContentType}"));
            }

            // Used to accumulate all the form url encoded key value pairs in the
            // request.
            var    formAccumulator = new KeyValueAccumulator();
            string targetFilePath  = null;

            var boundary = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(Request.ContentType),
                _defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader = new MultipartReader(boundary, HttpContext.Request.Body);

            var section = await reader.ReadNextSectionAsync();

            string   newFileName  = "";
            DateTime FileDateTime = new DateTime();

            while (section != null)
            {
                ContentDispositionHeaderValue contentDisposition;
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition);

                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        //targetFilePath = Path.GetTempFileName();

                        string fileName = contentDisposition.FileName.ToString().Trim('"');
                        newFileName    = FileHelper.newFileName(id, fileName, out FileDateTime);
                        targetFilePath = Path.Combine(_newPath, newFileName);
                        using (var targetStream = System.IO.File.Create(targetFilePath))
                        {
                            await section.Body.CopyToAsync(targetStream);

                            //  _logger.LogInformation($"Copied the uploaded file '{targetFilePath}'");
                        }
                    }
                    else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                    {
                        // Content-Disposition: form-data; name="key"
                        //
                        // value

                        // Do not limit the key name length here because the
                        // multipart headers length limit is already in effect.
                        var key      = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
                        var encoding = GetEncoding(section);
                        using (var streamReader = new StreamReader(
                                   section.Body,
                                   encoding,
                                   detectEncodingFromByteOrderMarks: true,
                                   bufferSize: 1024,
                                   leaveOpen: true))
                        {
                            // The value length limit is enforced by MultipartBodyLengthLimit
                            var value = await streamReader.ReadToEndAsync();

                            if (String.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
                            {
                                value = String.Empty;
                            }
                            formAccumulator.Append(key.ToString(), value);

                            if (formAccumulator.ValueCount > _defaultFormOptions.ValueCountLimit)
                            {
                                throw new InvalidDataException($"Form key count limit {_defaultFormOptions.ValueCountLimit} exceeded.");
                            }
                        }
                    }
                }

                //add the Trip File Object to the database
                //TripFile TripFileItem = new TripFile
                //{
                //    TripID = id,
                //    TripFileName = newFileName,
                //    FilePath = targetFilePath,
                //    FileDateTime = FileDateTime.ToString()
                //};
                //_context.Add(TripFileItem);
                //_context.SaveChanges();

                // Drains any remaining section body that has not been consumed and
                // reads the headers for the next section.
                section = await reader.ReadNextSectionAsync();
            }

            /// Bind form data to a model
            var formValueProvider = new FormValueProvider(
                BindingSource.Form,
                new FormCollection(formAccumulator.GetResults()),
                CultureInfo.CurrentCulture);

            return(new JsonResult(formValueProvider));
        }
Esempio n. 29
0
        public async Task <IActionResult> Upload()
        {
            var user = await base.GetAuthenticatedUserAsync();

            if (user == null)
            {
                return(base.UnauthorizedException());
            }

            // Ensure we are dealing with a multipart request
            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                return(BadRequest($"Expected a multipart request, but got {Request.ContentType}"));
            }

            // Used to accumulate all the form url
            // encoded key value pairs in the request.
            var formAccumulator = new KeyValueAccumulator();
            var boundary        = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(Request.ContentType),
                _defaultFormOptions.MultipartBoundaryLengthLimit);

            var reader = new MultipartReader(boundary, HttpContext.Request.Body);

            var  name          = string.Empty;
            var  contentType   = string.Empty;
            long contentLength = 0;

            byte[] bytes = null;

            var section = await reader.ReadNextSectionAsync();

            while (section != null)
            {
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);

                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        name        = contentDisposition.FileName.ToString();
                        contentType = section.ContentType;

                        // Create an in-memory stream to get the bytes and length
                        using (var ms = new MemoryStream())
                        {
                            // Read the seciton into our memory stream
                            await section.Body.CopyToAsync(ms);

                            // get bytes and length
                            bytes         = ms.StreamToByteArray();
                            contentLength = ms.Length;
                        }
                    }
                    else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                    {
                        // Content-Disposition: form-data; name="key" value
                        // Do not limit the key name length here because the
                        // multipart headers length limit is already in effect.

                        var key      = HeaderUtilities.RemoveQuotes(contentDisposition.Name).ToString();
                        var encoding = GetEncoding(section);

                        using (var streamReader = new StreamReader(
                                   section.Body,
                                   encoding,
                                   detectEncodingFromByteOrderMarks: true,
                                   bufferSize: 1024,
                                   leaveOpen: true))
                        {
                            // The value length limit is enforced by MultipartBodyLengthLimit
                            var value = await streamReader.ReadToEndAsync();

                            if (String.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
                            {
                                value = String.Empty;
                            }
                            formAccumulator.Append(key, value);

                            if (formAccumulator.ValueCount > _defaultFormOptions.ValueCountLimit)
                            {
                                throw new InvalidDataException($"Form key count limit {_defaultFormOptions.ValueCountLimit} exceeded.");
                            }
                        }
                    }
                }

                // Drains any remaining section body that has not been consumed and
                // reads the headers for the next section.
                section = await reader.ReadNextSectionAsync();
            }

            // Get btye array from memory stream for storage

            var output = new List <UploadedFile>();

            if (bytes == null)
            {
                return(BadRequest($"Could not obtain a byte array for the uploaded file."));
            }

            // Store media
            var media = await _mediaStore.CreateAsync(new Models.Media
            {
                Name          = name,
                ContentType   = contentType,
                ContentLength = contentLength,
                ContentBlob   = bytes,
                CreatedUserId = user.Id
            });

            // Build friendly results
            if (media != null)
            {
                output.Add(new UploadedFile()
                {
                    Id           = media.Id,
                    Name         = media.Name,
                    FriendlySize = media.ContentLength.ToFriendlyFileSize(),
                    IsImage      = IsContentTypeSupported(media.ContentType, SupportedImageContentTypes),
                    IsBinary     = IsContentTypeSupported(media.ContentType, SupportedBinaryContentTypes),
                });
            }

            return(base.Result(output));
        }
Esempio n. 30
0
        internal override async Task <Interfaces.ContextualBasket.IProcessingContext> Execute(HttpRequest request, Interfaces.ContextualBasket.IProcessingContext processingContext)
        {
            // Used to accumulate all the form url encoded key value pairs in the request.
            KeyValueAccumulator formAccumulator = new KeyValueAccumulator();
            string targetFilePath = null;

            string          s        = request.ContentType;
            string          boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(request.ContentType), _DefaultFormOptions.MultipartBoundaryLengthLimit);
            MultipartReader reader   = new MultipartReader(boundary, request.Body);

            MultipartSection section = await reader.ReadNextSectionAsync();

            while (section != null)
            {
                ContentDispositionHeaderValue contentDisposition;
                bool hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition);

                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        targetFilePath = Path.GetTempFileName();
                        using (var targetStream = System.IO.File.Create(targetFilePath))
                        {
                            await section.Body.CopyToAsync(targetStream);
                        }
                    }
                    else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                    {
                        // Content-Disposition: form-data; name="key" value

                        // Do not limit the key name length here because the
                        // multipart headers length limit is already in effect.
                        StringSegment key      = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
                        Encoding      encoding = GetEncoding(section);
                        using (var streamReader = new StreamReader(section.Body, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true))
                        {
                            // The value length limit is enforced by MultipartBodyLengthLimit
                            string value = await streamReader.ReadToEndAsync();

                            if (String.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
                            {
                                value = String.Empty;
                            }
                            formAccumulator.Append(key.ToString(), value);

                            if (formAccumulator.ValueCount > _DefaultFormOptions.ValueCountLimit)
                            {
                                throw new InvalidDataException($"Form key count limit {_DefaultFormOptions.ValueCountLimit} exceeded.");
                            }
                        }
                    }
                }

                // Drains any remaining section body that has not been consumed and reads the headers for the next section.
                section = await reader.ReadNextSectionAsync();
            }
            //else
            //{
            //    processingContext.ReturnModel.Status.StatusResults.Add(new StatusResult { StatusResultType = EStatusResult.StatusResultError, Message = "Current node is null or not OfType(View)" });
            //    throw new InvalidDataException("HtmlViewSynchronizeContextLocalImp.CurrentNode is null or not OfType(View)");
            //}
            return(await Task.FromResult(processingContext));

            //// Bind form data to a model
            //var formValueProvider = new FormValueProvider(
            //    BindingSource.Form,
            //    new FormCollection(formAccumulator.GetResults()),
            //    CultureInfo.CurrentCulture);
        }