首页 > 代码库 > webApi2 上传大文件代码
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有点上浮,上传速度有点慢,但比较稳定
webApi2 上传大文件代码
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。