Exemplo n.º 1
0
        protected async Task <Guid?> UploadFile()
        {
            var authorId = Guid.Parse(HttpContext.User.Identity.Name);

            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                return(null);
            }

            var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType), Constants.MultipartBoundaryLengthLimit);
            var reader   = new MultipartReader(boundary, HttpContext.Request.Body);
            var section  = await reader.ReadNextSectionAsync().ConfigureAwait(true);

            while (section != null)
            {
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);
                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        var nameHtmlEncoded = WebUtility.HtmlEncode(contentDisposition.FileName.Value);

                        return(await fileRepo.SaveAttachment(section, nameHtmlEncoded, authorId).ConfigureAwait(true));
                    }
                }

                section = await reader.ReadNextSectionAsync();
            }

            return(null);
        }
Exemplo n.º 2
0
        public async Task <IActionResult> Index()
        {
            try
            {
                var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType), DefaultFormOptions.MultipartBoundaryLengthLimit);
                var reader   = new MultipartReader(boundary, HttpContext.Request.Body);
                var section  = reader.ReadNextSectionAsync().Result;
                while (section != null)
                {
                    ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        var fileNameUpload = HeaderUtilities.RemoveQuotes(contentDisposition.FileName).Value;
                        var bytes          = StreamToBytes(section.Body);
                        var result         = await _fileAppService.Upload(fileNameUpload, bytes);

                        return(Json(result));
                    }
                    section = await reader.ReadNextSectionAsync();
                }
                return(NoContent());
            }
            catch (Exception e)
            {
                return(StatusCode(500, e.Message));
            }
        }
 private static IEnumerable <ValidationResult> HasFileContentDispositionValidation(ContentDispositionHeaderValue contentDisposition)
 {
     if (!MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
     {
         yield return(new ValidationResult($"The request couldn't be processed (Error 2).", new[] { "File" }));
     }
 }
Exemplo n.º 4
0
        public async Task <string> SaveVideoAsync(MultipartSection section)
        {
            var hasContentDisposition = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);

            if (!hasContentDisposition)
            {
                throw new ArgumentNullException();
            }
            if (!MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
            {
                throw new ArgumentNullException();
            }

            var name           = HeaderUtilities.RemoveQuotes(contentDisposition.FileName).Value.Trim();
            var targetFilePath = $"{HostingEnvironment.WebRootPath}/{name}";

            if (System.IO.File.Exists(targetFilePath))
            {
                System.IO.File.Delete(targetFilePath);
            }

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

            var id = Path.GetFileNameWithoutExtension(name);

            return(id);
        }
Exemplo n.º 5
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log, ExecutionContext context)
        {
            #region Config
            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();

            string storageConnectionString = config["AzureWebJobsStorage"];
            #endregion

            #region Setting Up Cloud Storage
            CloudStorageAccount.TryParse(storageConnectionString, out CloudStorageAccount storageAccount);
            CloudBlobClient cloudBlobClient    = storageAccount.CreateCloudBlobClient();
            var             cloudBlobContainer = cloudBlobClient.GetContainerReference("tempphotos");
            await cloudBlobContainer.CreateIfNotExistsAsync();

            BlobContainerPermissions permissions = new BlobContainerPermissions
            {
                PublicAccess = BlobContainerPublicAccessType.Blob
            };
            await cloudBlobContainer.SetPermissionsAsync(permissions);

            #endregion

            #region Multipart Receive and Upload
            List <string> filesUploaded = new List <string>();
            var           boundary      = MultipartRequestHelper.GetBoundary(Microsoft.Net.Http.Headers.MediaTypeHeaderValue.Parse(req.ContentType), int.MaxValue);
            var           reader        = new MultipartReader(boundary, req.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 && MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                {
                    CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(contentDisposition.FileName.Value);
                    await cloudBlockBlob.UploadFromStreamAsync(section.Body);

                    filesUploaded.Add(cloudBlockBlob.Uri.ToString());
                }
                section = await reader.ReadNextSectionAsync();
            }
            #endregion

            #region Return JSON
            var jsonToReturn = JsonConvert.SerializeObject(filesUploaded.ToArray());

            return(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(jsonToReturn, Encoding.UTF8, "application/json")
            });

            #endregion
        }
Exemplo n.º 6
0
        public async Task <ActionResult> UpLoadAndProcessFile()
        {
            string id         = System.Guid.NewGuid().ToString();
            string _extension = string.Empty;

            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                ModelState.AddModelError("File", "非法请求或请求的格式不正确.");
                return(BadRequest(ModelState));
            }
            MediaTypeHeaderValue headerValue = MediaTypeHeaderValue.Parse(Request.ContentType);
            var boundary = MultipartRequestHelper.GetBoundary(headerValue, 2097152);

            if (string.IsNullOrEmpty(boundary))
            {
                ModelState.AddModelError("ContentType", "Missing content-type boundary.");
                return(BadRequest(ModelState));
            }

            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 untrustedFileNameForStorage = string.Empty;
                        var trustedFileNameForDisplay = string.Empty;
                        //untrustedFileNameForStorage = contentDisposition.FileName.Value;
                        trustedFileNameForDisplay = WebUtility.HtmlEncode(contentDisposition.FileName.Value);
                        _extension = Path.GetExtension(trustedFileNameForDisplay);
                        var streamContent = await FileUploadHelper.ProcessStreamFile(section, contentDisposition, ModelState, 2097152);

                        if (!ModelState.IsValid)
                        {
                            return(BadRequest(ModelState));
                        }
                        string zipFilePath          = $"jmx/{id}{_extension}";
                        string extractDirectoryPath = $"jmx/{id}";
                        using (var targetStream = System.IO.File.Create(zipFilePath))
                        {
                            await targetStream.WriteAsync(streamContent);
                        }
                        bool extract = await FileOperaHelper.ExtractToDirectory(zipFilePath, extractDirectoryPath, true);

                        if (!extract)
                        {
                            ModelState.AddModelError("message", "文件解压失败");
                            return(BadRequest(ModelState));
                        }
                    }
                }

                section = await reader.ReadNextSectionAsync();
            }
            return(Ok(new { code = "1", message = "上传成功", path = $"jmx/{id}{_extension}" }));
        }
        public async Task <IActionResult> UploadPhysical([FromQuery] Guid uploadId)
        {
            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                ModelState.AddModelError("File", $"The request couldn't be processed (Error 1).");

                return(BadRequest(ModelState));
            }

            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)
                {
                    // This check assumes that there's a file
                    // present without form data. If form data
                    // is present, this method immediately fails
                    // and returns the model error.
                    if (!MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        ModelState.AddModelError("File", $"The request couldn't be processed (Error 2).");
                        return(BadRequest(ModelState));
                    }
                    else
                    {
                        var streamedFileContent = await FileHelpers.ProcessStreamedFile(section, contentDisposition, ModelState);

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

                        var filePath       = Path.Combine(_targetFilePath, uploadId.ToString(), contentDisposition.FileName.Value);
                        var fileFolderPath = Path.GetDirectoryName(filePath);

                        if (!Directory.Exists(fileFolderPath))
                        {
                            Directory.CreateDirectory(fileFolderPath);
                        }

                        using (var targetStream = System.IO.File.Create(filePath))
                        {
                            await targetStream.WriteAsync(streamedFileContent);
                        }
                    }
                }

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

            return(Created(nameof(StreamingController), null));
        }
Exemplo n.º 8
0
            public async Task <Response> Handle(Request request, CancellationToken cancellationToken)
            {
                var httpContext        = _httpContextAccessor.HttpContext;
                var defaultFormOptions = new FormOptions();
                var digitalAssets      = new List <DigitalAsset>();

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

                var mediaTypeHeaderValue = MediaTypeHeaderValue.Parse(httpContext.Request.ContentType);

                var boundary = MultipartRequestHelper.GetBoundary(
                    mediaTypeHeaderValue,
                    defaultFormOptions.MultipartBoundaryLengthLimit);

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

                var section = await reader.ReadNextSectionAsync();

                while (section != null)
                {
                    DigitalAsset digitalAsset = default;

                    var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out ContentDispositionHeaderValue contentDisposition);

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

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

                                digitalAsset = new DigitalAsset(name, bytes, contentType);
                            }
                        }
                    }

                    _context.DigitalAssets.Add(digitalAsset);

                    digitalAssets.Add(digitalAsset);

                    section = await reader.ReadNextSectionAsync();
                }

                await _context.SaveChangesAsync(cancellationToken);

                return(new()
                {
                    DigitalAssetIds = digitalAssets.Select(x => x.DigitalAssetId).ToList()
                });
            }
        public async Task <FileAccumulator> UploadFileAsync(MultipartReader reader)
        {
            try
            {
                var filename = Guid.NewGuid().ToString();
                using (var destinationStream = await _context.GetBucket().OpenUploadStreamAsync(filename))
                {
                    var id      = destinationStream.Id; // the unique Id of the file being uploaded
                    var section = await reader.ReadNextSectionAsync();

                    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);
                            }
                        }
                        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 FileAccumulator
                    {
                        Id = id.ToString(),
                        Filename = filename
                    });
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(null);
            }
        }
        public async Task <ResponseModel> Handle(MultipleFileUploadCommand request, CancellationToken cancellationToken)
        {
            var errorModel = new FormFileErrorModel();

            if (!MultipartRequestHelper.IsMultipartContentType(_accessor.HttpContext.Request.ContentType))
            {
                errorModel.Errors.Add("File",
                                      $"The request couldn't be processed (Error 1).");

                return(ResponseProvider.Ok(errorModel));
            }
            var boundary = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(_accessor.HttpContext.Request.ContentType),
                _defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader  = new MultipartReader(boundary, _accessor.HttpContext.Request.Body);
            var section = await reader.ReadNextSectionAsync(cancellationToken);

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

                if (hasContentDispositionHeader)
                {
                    if (!MultipartRequestHelper
                        .HasFileContentDisposition(contentDisposition))
                    {
                        errorModel.Errors.Add("File", $"The request couldn't be processed (Error 2).");

                        return(ResponseProvider.Ok(errorModel));
                    }
                    else
                    {
                        var streamedFileContent = await FileHelpers.ProcessStreamedFile(
                            section, contentDisposition, errorModel,
                            _permittedExtensions, _streamFileLimitSize, ValidateExtension.Encrypt);

                        if (errorModel.Errors.Any())
                        {
                            return(ResponseProvider.Ok(errorModel));
                        }
                        var fileName = FileHelpers.GetFileName(section.ContentDisposition);

                        var fileNameWithEncryptExtension = UploadFileHelper.GetFileNameWithEncryptExtension(fileName, request.EncryptAlg);
                        var uploadFileAbsolutePath       = UploadFileHelper.GetUploadAbsolutePath(_contentRootPath, fileNameWithEncryptExtension, request.Archive);

                        await UploadFile(streamedFileContent, uploadFileAbsolutePath, request.EncryptAlg);
                    }
                }

                section = await reader.ReadNextSectionAsync(cancellationToken);
            }

            return(ResponseProvider.Ok("Upload file successfully"));
        }
Exemplo n.º 11
0
        public void MultipartRequestHelperTest_HasFileContentDisposition()
        {
            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(true, MultipartRequestHelper.HasFileContentDisposition(formdata));
        }
Exemplo n.º 12
0
        public async Task <ActionResult <BlobInfo[]> > UploadAssetToLocalFileSystemAsync()
        {
            //ToDo Now supports downloading one file, find a solution for downloading multiple files
            // https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-3.1
            var result = new List <BlobInfo>();

            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                return(BadRequest($"Expected a multipart request, but got {Request.ContentType}"));
            }
            var uploadPath = Path.GetFullPath(_platformOptions.LocalUploadFolderPath);

            if (!Directory.Exists(uploadPath))
            {
                Directory.CreateDirectory(uploadPath);
            }

            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)
            {
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);

                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        var fileName       = contentDisposition.FileName.Value;
                        var targetFilePath = Path.Combine(uploadPath, fileName);

                        if (!Directory.Exists(uploadPath))
                        {
                            Directory.CreateDirectory(uploadPath);
                        }

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

                        var blobInfo = AbstractTypeFactory <BlobInfo> .TryCreateInstance();

                        blobInfo.Name = fileName;
                        //Use only file name as Url, for further access to these files need use PlatformOptions.LocalUploadFolderPath
                        blobInfo.Url         = fileName;
                        blobInfo.ContentType = MimeTypeResolver.ResolveContentType(fileName);
                        result.Add(blobInfo);
                    }
                }
            }
            return(Ok(result.ToArray()));
        }
        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));
        }
Exemplo n.º 14
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));
            }
        }
Exemplo n.º 15
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 }));
        }
Exemplo n.º 16
0
        public static async System.Threading.Tasks.Task <ICollection <DigitalAsset> > Upload(IHttpContextAccessor httpContextAccessor, IAppDbContext context, CancellationToken cancellationToken)
        {
            var httpContext        = httpContextAccessor.HttpContext;
            var defaultFormOptions = new FormOptions();
            var digitalAssets      = new List <DigitalAsset>();

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

            var mediaTypeHeaderValue = MediaTypeHeaderValue.Parse(httpContext.Request.ContentType);

            var boundary = MultipartRequestHelper.GetBoundary(
                mediaTypeHeaderValue,
                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 ContentDispositionHeaderValue contentDisposition);

                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper.HasFileContentDisposition(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 contentType = section.ContentType;

                            var digitalAsset = new DigitalAsset(name, bytes, contentType);

                            context.Store(digitalAsset);

                            digitalAssets.Add(digitalAsset);
                        }
                    }
                }

                section = await reader.ReadNextSectionAsync(cancellationToken);
            }

            await context.SaveChangesAsync(cancellationToken);

            return(digitalAssets);
        }
Exemplo n.º 17
0
        public async Task <IActionResult> UploadBotAsync()
        {
            var appPath        = Environment.GetEnvironmentVariable("APP_PATH");
            var botRootCatalog = Path.Combine(appPath, "bots");

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

            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);

                var fileName = contentDisposition.FileName.ToString();
                if (!IsValidFileName(fileName))
                {
                    throw new ArgumentException($"Имя имя '{fileName}' не является корректным именем файла.");
                }

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

                            copyStream.Seek(0, SeekOrigin.Begin);
                            using (var targetStream = System.IO.File.Create(botRootCatalog))
                            {
                                await copyStream.CopyToAsync(targetStream).ConfigureAwait(false);
                            }
                        }
                    }
                }

                section = await reader.ReadNextSectionAsync();
            }

            return(BadRequest());
        }
Exemplo n.º 18
0
        public async Task <IActionResult> Upload()
        {
            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                return(BadRequest($"Expected a multipart request, but got {Request.ContentType}"));
            }

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

            // In this concept, only one file-content in the Request content is supported.
            Guid id = Guid.NewGuid();

            var section = await reader.ReadNextSectionAsync();

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

                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        var contentDestinationPath = Path.Combine(_persistenceLocation, $"{id}");
                        var metaDestinationPath    = Path.Combine(_persistenceLocation, $"{id}.meta");

                        // TODO: persistence should be configurable; filesystem or database.

                        using (var metaFile = System.IO.File.Create(metaDestinationPath))
                        {
                            using (var sw = new StreamWriter(metaFile))
                            {
                                sw.WriteLine("originalfilename:" + Path.GetFileName(contentDisposition.FileName.Trim('\"')));
                            }
                        }

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

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

            return(new OkObjectResult(new UploadResult(id.ToString())));
        }
Exemplo n.º 19
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);
        }
        public async Task <IActionResult> ImportCsv()
        {
            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                return(BadRequest("The request must be multipart"));
            }

            string boundary = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(Request.ContentType),
                new FormOptions().MultipartBoundaryLengthLimit);

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

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

                if (!hasContentDispositionHeader)
                {
                    section = await reader.ReadNextSectionAsync();

                    continue;
                }

                if (!MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                {
                    return(BadRequest("The file must have Content-Disposition: form-data"));
                }

                var command = new SaveCsvToImportCommand
                {
                    //InputFile = file,
                    InputStream = section.Body,
                    FileName    = contentDisposition.FileName.Value
                };

                await _mediator.Send(command);

                section = await reader.ReadNextSectionAsync();
            }

            return(Ok());
        }
Exemplo n.º 21
0
        ReadFileContent(this MultipartReader reader)
        {
            var section = reader.ReadNextSectionAsync().Result;

            while (section != null)
            {
                if (ContentDispositionHeaderValue
                    .TryParse(section.ContentDisposition,
                              out var contentDisposition))
                {
                    if (MultipartRequestHelper
                        .HasFileContentDisposition(contentDisposition))
                    {
                        yield return(section);
                    }
                }
                // TODO: Invalid opration exception when already read
                section = reader.ReadNextSectionAsync().Result;
            }
        }
Exemplo n.º 22
0
        protected async Task <ApiResult <(Stream FileContent, string FileName)> > LoadFile()
        {
            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                return(ApiResult <(Stream FileContent, string FileName)> .Failure(
                           $"The request couldn't be processed because of ContentType: {Request.ContentType}",
                           HttpStatusCode.BadRequest));
            }

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

            var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);

            if (!hasContentDispositionHeader)
            {
                return(ApiResult <(Stream FileContent, string FileName)> .Failure(
                           "The request couldn't be processed because of absent ContentDisposition",
                           HttpStatusCode.BadRequest));
            }

            // This check assumes that there's a file present without form data.
            // If form data is present, this method immediately fails and returns the model error.
            if (!MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
            {
                return(ApiResult <(Stream FileContent, string FileName)> .Failure(
                           $"The request couldn't be processed because of ContentDisposition {contentDisposition}",
                           HttpStatusCode.BadRequest));
            }

            var streamedFileContent = section.Body;

            if (!ModelState.IsValid)
            {
                return(ApiResult <(Stream FileContent, string FileName)> .Failure("", HttpStatusCode.BadRequest));
            }

            return(ApiResult <(Stream FileContent, string FileName)>
                   .Success((streamedFileContent, contentDisposition.FileName.Value)));
        }
Exemplo n.º 23
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
            }));
        }
        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 }));
        }
Exemplo 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 }));
        }
Exemplo n.º 26
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 }));
        }
        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);
        }
Exemplo n.º 28
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));
        }
        //[DisableFormValueModelBinding]
        //[ValidateAntiForgeryToken]
        public async Task <IActionResult> UploadPhysical()
        {
            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                ModelState.AddModelError("File",
                                         $"The request couldn't be processed (Error 1).");
                // Log error

                return(BadRequest(ModelState));
            }

            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)
                {
                    // This check assumes that there's a file
                    // present without form data. If form data
                    // is present, this method immediately fails
                    // and returns the model error.
                    if (!MultipartRequestHelper
                        .HasFileContentDisposition(contentDisposition))
                    {
                        ModelState.AddModelError("File",
                                                 $"The request couldn't be processed (Error 2).");
                        // Log error

                        return(BadRequest(ModelState));
                    }
                    else
                    {
                        // Don't trust the file name sent by the client. To display
                        // the file name, HTML-encode the value.
                        var trustedFileNameForDisplay = WebUtility.HtmlEncode(
                            contentDisposition.FileName.Value);
                        var trustedFileNameForFileStorage = Path.GetRandomFileName();

                        // **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.

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

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

                        using (var targetStream = System.IO.File.Create(
                                   Path.Combine(_targetFilePath, trustedFileNameForFileStorage)))
                        {
                            await targetStream.WriteAsync(streamedFileContent);

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

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

            return(Created(nameof(HomeController), null));
        }
Exemplo n.º 30
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));
            }
        }