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有点上浮,上传速度有点慢,但比较稳定

posted on 2014-10-22 11:14  ~紫鱼~  阅读(3163)  评论(2编辑  收藏  举报