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 =https://www.cnblogs.com/hts92/p/ _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的回收.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/91630.html
標籤:.NET Core
