1. 程式人生 > >NetCore3.0 檔案上傳與大檔案上傳的限制

NetCore3.0 檔案上傳與大檔案上傳的限制

NetCore檔案上傳兩種方式

  NetCore官方給出的兩種檔案上傳方式分別為“緩衝”、“流式”。我簡單的說說兩種的區別,

  1.緩衝:通過模型繫結先把整個檔案儲存到記憶體,然後我們通過IFormFile得到stream,優點是效率高,缺點對記憶體要求大。檔案不宜過大。

  2.流式處理:直接讀取請求體裝載後的Section 對應的stream 直接操作strem即可。無需把整個請求體讀入記憶體,

以下為官方微軟說法

緩衝

  整個檔案讀入 IFormFile,它是檔案的 C# 表示形式,用於處理或儲存檔案。 檔案上傳所用的資源(磁碟、記憶體)取決於併發檔案上傳的數量和大小。 如果應用嘗試緩衝過多上傳,站點就會在記憶體或磁碟空間不足時崩潰。 如果檔案上傳的大小或頻率會消耗應用資源,請使用流式傳輸。

流式處理   

  從多部分請求收到檔案,然後應用直接處理或儲存它。 流式傳輸無法顯著提高效能。 流式傳輸可降低上傳檔案時對記憶體或磁碟空間的需求。

檔案大小限制

  說起大小限制,我們得從兩方面入手,1應用伺服器Kestrel 2.應用程式(我們的netcore程式),

1.應用伺服器Kestre設定

  應用伺服器Kestrel對我們的限制主要是對整個請求體大小的限制通過如下配置可以進行設定(Program -> CreateHostBuilder),超出設定範圍會報 BadHttpRequestException: Request body too large 異常資訊

public static IHostBuilder CreateHostBuilder(string[] args) =>
           Host.CreateDefaultBuilder(args)
               .ConfigureWebHostDefaults(webBuilder =>
               {
                   webBuilder.ConfigureKestrel((context, options) =>
                   {
                       //設定應用伺服器Kestrel請求體最大為50MB
                       options.Limits.MaxRequestBodySize = 52428800;
                   });
                   webBuilder.UseStartup<Startup>();
});

2.應用程式設定

  應用程式設定 (Startup->  ConfigureServices) 超出設定範圍會報InvalidDataException 異常資訊

services.Configure<FormOptions>(options =>
 {
             options.MultipartBodyLengthLimit = long.MaxValue;
 });

通過設定即重置檔案上傳的大小限制。

原始碼分析

  這裡我主要說一下 MultipartBodyLengthLimit  這個引數他主要限制我們使用“緩衝”形式上傳檔案時每個的長度。為什麼說是緩衝形式中,是因為我們緩衝形式在讀取上傳檔案用的幫助類為 MultipartReaderStream 類下的 Read 方法,此方法在每讀取一次後會更新下讀入的總byte數量,當超過此數量時會丟擲  throw new InvalidDataException($"Multipart body length limit {LengthLimit.GetValueOrDefault()} exceeded.");  主要體現在 UpdatePosition 方法對 _observedLength  的判斷

以下為 MultipartReaderStream 類兩個方法的原始碼,為方便閱讀,我已精簡掉部分程式碼

Read

public override int Read(byte[] buffer, int offset, int count)
 {
          
          var bufferedData = _innerStream.BufferedData;
      int read;
      read = _innerStream.Read(buffer, offset, Math.Min(count, bufferedData.Count));
          return UpdatePosition(read);
}

UpdatePosition

private int UpdatePosition(int read)
        {
            _position += read;
            if (_observedLength < _position)
            {
                _observedLength = _position;
                if (LengthLimit.HasValue && _observedLength > LengthLimit.GetValueOrDefault())
                {
                    throw new InvalidDataException($"Multipart body length limit {LengthLimit.GetValueOrDefault()} exceeded.");
                }
            }
            return read;
}

通過程式碼我們可以看到 當你做了 MultipartBodyLengthLimit 的限制後,在每次讀取後會累計讀取的總量,當讀取總量超出

 MultipartBodyLengthLimit  設定值會丟擲 InvalidDataException 異常,

最終我的檔案上傳Controller如下

  需要注意的是我們建立 MultipartReader 時並未設定 BodyLengthLimit  (這引數會傳給 MultipartReaderStream.LengthLimit )也就是我們最終的限制,這裡我未設定值也就無限制,可以通過 UpdatePosition 方法體現出來

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Net.Http.Headers;
using System.IO;
using System.Threading.Tasks;
 
namespace BigFilesUpload.Controllers
{
    [Route("api/[controller]")]
    public class FileController : Controller
    {
        private readonly string _targetFilePath = "C:\\files\\TempDir";
 
        /// <summary>
        /// 流式檔案上傳
        /// </summary>
        /// <returns></returns>
        [HttpPost("UploadingStream")]
        public async Task<IActionResult> UploadingStream()
        {
 
            //獲取boundary
            var boundary = HeaderUtilities.RemoveQuotes(MediaTypeHeaderValue.Parse(Request.ContentType).Boundary).Value;
            //得到reader
            var reader = new MultipartReader(boundary, HttpContext.Request.Body);
            //{ BodyLengthLimit = 2000 };//
            var section = await reader.ReadNextSectionAsync();
 
            //讀取section
            while (section != null)
            {
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);
                if (hasContentDispositionHeader)
                {
                    var trustedFileNameForFileStorage = Path.GetRandomFileName();
                    await WriteFileAsync(section.Body, Path.Combine(_targetFilePath, trustedFileNameForFileStorage));
                }
                section = await reader.ReadNextSectionAsync();
            }
            return Created(nameof(FileController), null);
        }
 
        /// <summary>
        /// 快取式檔案上傳
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        [HttpPost("UploadingFormFile")]
        public async Task<IActionResult> UploadingFormFile(IFormFile file)
        {
            using (var stream = file.OpenReadStream())
            {
                var trustedFileNameForFileStorage = Path.GetRandomFileName();
                await WriteFileAsync(stream, Path.Combine(_targetFilePath, trustedFileNameForFileStorage));
            }
            return Created(nameof(FileController), null);
        }
 
 
        /// <summary>
        /// 寫檔案導到磁碟
        /// </summary>
        /// <param name="stream">流</param>
        /// <param name="path">檔案儲存路徑</param>
        /// <returns></returns>
        public static async Task<int> WriteFileAsync(System.IO.Stream stream, string path)
        {
            const int FILE_WRITE_SIZE = 84975;//寫出緩衝區大小
            int writeCount = 0;
            using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Write, FILE_WRITE_SIZE, true))
            {
                byte[] byteArr = new byte[FILE_WRITE_SIZE];
                int readCount = 0;
                while ((readCount = await stream.ReadAsync(byteArr, 0, byteArr.Length)) > 0)
                {
                    await fileStream.WriteAsync(byteArr, 0, readCount);
                    writeCount += readCount;
                }
            }
            return writeCount;
        }
 
    }
}

 

 總結:

如果你部署 在iis上或者Nginx 等其他應用伺服器 也是需要注意的事情,因為他們本身也有對請求體的限制,還有值得注意的就是我們在建立檔案流物件時 緩衝區的大小盡量不要超過netcore大物件的限制。這樣在併發高的時候很容易觸發二代GC的回收.