上傳大文件,取消內存緩存:
GlobalConfiguration.Configuration.Services.Replace(typeof(IHostBufferPolicySelector), new CustomPolicy());
public class CustomPolicy : WebHostBufferPolicySelector { #region Public Methods and Operators public override bool UseBufferedInputStream(object hostContext) { return false; } #endregion }
上傳代碼:
[HttpPost] [Route("api/upload")] public async Task<int> PostFormData() { // Check if the request contains multipart/form-data. if(!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } string root = HttpContext.Current.Server.MapPath("~/Uploads/"); MyStreamProvider streamProvider = new MyStreamProvider(root); //var provider = new MultipartFormDataStreamProvider(root); try { // Read the form data. await Request.Content.ReadAsMultipartAsync(streamProvider); // This illustrates how to get the file names. //foreach(MultipartFileData file in streamProvider.FileData) { // Trace.WriteLine(file.Headers.ContentDisposition.Size); // Trace.WriteLine("Server file path: " + file.LocalFileName); //} FileInfo fileInfo = new FileInfo(streamProvider.FileData[0].LocalFileName); } catch(System.Exception e) { throw e; } }
經測試上傳:大文件,內存消耗不多,CPU有點上浮,上傳速度有點慢,但比較穩定