Exemplo n.º 1
0
        private static async Task <KeyValueAccumulator> UploadImageLargeRefactor(KeyValueAccumulator formAccumulator, MultipartSection section, ContentDispositionHeaderValue 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 = MultipartRequestHelper.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().ConfigureAwait(false);

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

                if (formAccumulator.ValueCount > _defaultFormOptions.ValueCountLimit)
                {
                    throw new InvalidDataException(string.Format(MessagesConstants.FormCountLimitExceeded, _defaultFormOptions.ValueCountLimit));
                }
            }

            return(formAccumulator);
        }
        private static async Task <KeyValueAccumulator> AccumulateForm(KeyValueAccumulator formAccumulator, MultipartSection section,
                                                                       ContentDispositionHeaderValue contentDisposition)
        {
            var key      = MultipartRequestHelper.RemoveQuotes(contentDisposition.Name.Value);
            var encoding = MultipartRequestHelper.GetEncoding(section);

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

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

                formAccumulator.Append(key, value);

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

            return(formAccumulator);
        }
        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;
            }
        }
Exemplo n.º 4
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();
            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 = _configuration.MusicFilePath + contentDisposition.FileName.Substring(1, contentDisposition.FileName.Length - 2);
                        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 = MultipartRequestHelper.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.Buffer, 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(uploadedData));
        }
        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();

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

                var targetFileDirectory = Path.Combine(_hostingEnvironment.ContentRootPath, "Uploads");
                if (!Directory.Exists(targetFileDirectory))
                {
                    Directory.CreateDirectory(targetFileDirectory);
                }

                var section = await reader.ReadNextSectionAsync();

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

                    if (hasContentDispositionHeader)
                    {
                        if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                        {
                            var fileName = HeaderUtilities.RemoveQuotes(contentDisposition.FileName).Value;
                            var filePath = Path.Combine(targetFileDirectory, fileName);

                            formAccumulator.Append("FileName", fileName);
                            formAccumulator.Append("FilePath", filePath);

                            using (var targetStream = System.IO.File.Create(filePath))
                            {
                                await section.Body.CopyToAsync(targetStream);

                                _logger.LogInformation($"Copied the uploaded file '{filePath}'");
                            }
                        }
                        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 = MultipartRequestHelper.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();
                }

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

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

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

                var dataFileId = _context.DataFile
                                 .AsNoTracking()
                                 .Where(el => el.FileName == dataFile.FileName || el.FilePath == dataFile.FilePath)
                                 .Select(el => el.Id)
                                 .SingleOrDefault();

                if (dataFileId == 0)
                {
                    _context.DataFile.Add(dataFile);
                    _context.SaveChanges();
                    dataFileId = dataFile.Id;
                }
                else
                {
                    var df = _context.DataFile.Find(dataFileId);
                    df.FilePath = dataFile.FilePath;
                    df.FileName = dataFile.FileName;
                }

                var(lineItems, errorList) = ExcelHelper.ConvertCsVtoDataTable(dataFile.FilePath, dataFileId);
                var listItems = lineItems;
                var errors    = errorList;

                System.IO.File.Delete(dataFile.FilePath);

                if (errors != null && errors.Any())
                {
                    var          conn  = _context.Database.GetDbConnection();
                    const string query = @"DELETE FROM ERRORLIST;
                                           ALTER TABLE ERRORLIST AUTO_INCREMENT = 1";
                    conn.Execute(query);
                    _context.ErrorList.AddRange(errorList);
                    _context.SaveChanges();
                    return(Json(1));
                }

                if (listItems != null && listItems.Any())
                {
                    var          conn  = _context.Database.GetDbConnection();
                    const string query = @"DELETE FROM TempData;
                                           ALTER TABLE TempData AUTO_INCREMENT = 1";
                    conn.Execute(query);

                    _context.TempData.AddRange(listItems);
                    _context.SaveChanges();

                    return(RedirectToAction("IsDescriptionMapped", "Mapping"));
                }

                return(BadRequest());
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }