Dealing with large file uploads on ASP.NET Core 1.0

前端 未结 3 576
闹比i
闹比i 2020-12-04 17:52

When I\'m uploading large files to my web api in ASP.NET Core, the runtime will load the file into memory before my function for processing and storing the upload is fired.

3条回答
  •  眼角桃花
    2020-12-04 18:46

    Shaun Luttin's answer is great, and now much of the work he's demonstrated is provided by ASP.Net Core 2.2.

    Get the boundary:

    // Microsoft.AspNetCore.Http.Extensions.HttpRequestMultipartExtensions
    var boundary = Request.GetMultipartBoundary();
    
    if (string.IsNullOrWhiteSpace(boundary))
      return BadRequest();
    

    You still get a section as follows:

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

    Check the disposition and convert to FileMultipartSection:

    if (section.GetContentDispositionHeader())
    {
         var fileSection = section.AsFileSection();
         var fileName = fileSection.FileName;
    
         using (var stream = new FileStream(fileName, FileMode.Append))
             await fileSection.FileStream.CopyToAsync(stream);
    }
    

提交回复
热议问题