WebApi FormData+文件长传 异步+同步实现

 // POST api/values
        public async Task Post()
        {
            try
            {
                // 检查该请求是否含有multipart/form-data
                if (!Request.Content.IsMimeMultipartContent())
                {
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }
                // 方法一
                System.Web.HttpFileCollection file = System.Web.HttpContext.Current.Request.Files;
                if (file.Count > 0)
                {
                    //文件名  
                    string name = file[0].FileName;
                    //保存文件  
                    string path = HttpContext.Current.Server.MapPath("~/") + name;
                    file[0].SaveAs(path);
                }

                Dictionary<string, string> dicFormData = new Dictionary<string, string>();
                foreach (var key in System.Web.HttpContext.Current.Request.Form.AllKeys)
                {
                    //接收FormData  
                    dicFormData.Add(key, System.Web.HttpContext.Current.Request.Form[key]);
                }

                // 方法二
                Dictionary<string, string> dic = new Dictionary<string, string>();
                string root = HttpContext.Current.Server.MapPath("~/App_Data");//指定要将文件存入的服务器物理位置  
                var provider = new MultipartFormDataStreamProvider(root);
                // Read the form data.  
                await Request.Content.ReadAsMultipartAsync(provider);

                // This illustrates how to get the file names.  
                foreach (MultipartFileData file1 in provider.FileData)
                {//接收文件  
                    Trace.WriteLine(file1.Headers.ContentDisposition.FileName);//获取上传文件实际的文件名  
                    Trace.WriteLine("Server file path: " + file1.LocalFileName);//获取上传文件在服务上默认的文件名  
                }
                foreach (var key in provider.FormData.AllKeys)
                {//接收FormData  
                    dic.Add(key, provider.FormData[key]);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

 

posted @ 2018-10-17 23:48  昨日微风  阅读(925)  评论(0编辑  收藏