码迷,mamicode.com
首页 > Windows程序 > 详细

webApi2 上传大文件代码

时间:2014-10-22 12:30:47      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   for   sp   

上传大文件,取消内存缓存:

    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 上传大文件代码

标签:style   blog   http   color   io   os   ar   for   sp   

原文地址:http://www.cnblogs.com/flyfish2012/p/4042605.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!