Ejemplo n.º 1
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));
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> OnPostAsync()
        {
            var supportedTypes = new[] { "mp4", "webm", "ogg", "mov", "mkv", "avi", "wmv", "m4v" };
            var fileExt        = Path.GetExtension(Submission.FormFile.FileName).Substring(1);

            if (!supportedTypes.Contains(fileExt))
            {
                ModelState.AddModelError("Submission.FileName", "File must be in mp4, m4v, wmv, avi, mkv, mov, webm, or ogg format.");
            }

            if (!Submission.ImageConsent)
            {
                ModelState.AddModelError("Submission.ImageConsent", "You must agree to the image consent.");
            }

            if (!Submission.ContestConsent)
            {
                ModelState.AddModelError("Submission.ContestConsent", "You must agree to the contest consent.");
            }

            if (!ModelState.IsValid)
            {
                Submission.FileName = Submission.FormFile.FileName;
                var locations = await _context.Locations.OrderBy(e => e.Name).ToListAsync();

                LocationSl = new SelectList(locations, nameof(Location.Id), nameof(Location.Name), "0");
                Submission.ErrorMessage = "Your entry was not successful.";
                return(Page());
            }

            var contentType = Submission.FormFile.ContentType;

            using (var fileStream = Submission.FormFile.OpenReadStream())
            {
                var fileName =
                    await _storage.StoreAndGetFile(Submission.FormFile.FileName, "talentcontest", contentType, fileStream);

                Submission.FileName = fileName;
            }

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

            _context.Submissions.Add(sub);
            await _context.SaveChangesAsync();

            var guid = sub.StringId;

            return(RedirectToPage("ThankYou", new { id = guid }));
        }