webApi2 上传大文件代码
上传大文件,取消内存缓存:
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有点上浮,上传速度有点慢,但比较稳定
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步