.Net WebAPI FormData 上传文件实现

前台Html

 

WebApi后台代码

解析FormData方式一

 [HttpPost,Route("PostFormData")]
        public async Task PostFormData()
        {
            ApiResult apiResult = new ApiResult();
            // Check if the request contains multipart/form-data.
            // 检查该请求是否含有multipart/form-data
            if (!Request.Content.IsMimeMultipartContent())
            {
                //throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                apiResult.code = 415;
            }
            string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data");           
            try
            {
                var multipartMemoryStreamProvider = await Request.Content.ReadAsMultipartAsync();
                var contentsList = multipartMemoryStreamProvider.Contents;
                var fileKeyList = contentsList.Where(x => !string.IsNullOrEmpty(x.Headers.ContentDisposition.FileName)).ToList();
                var formDataList= contentsList.Where(x => string.IsNullOrEmpty(x.Headers.ContentDisposition.FileName)).ToList();
                Dictionary dic = new Dictionary();
                foreach (var content in multipartMemoryStreamProvider.Contents)
                {
                    //通过判断fileName是否为空,判断是否为文件类型
                    if (!string.IsNullOrEmpty(content.Headers.ContentDisposition.FileName))
                    {
                        string fileName = content.Headers.ContentDisposition.FileName.Replace("\"", string.Empty);
                        using (Stream stream = await content.ReadAsStreamAsync())
                        {
                            byte[] bytes = new byte[stream.Length];
                            stream.Read(bytes, 0, bytes.Length);
                            stream.Seek(0, SeekOrigin.Begin);
                            CommonUtils.SaveFile(bytes,root+@"\"+fileName);//保存文件
                        }
                    }
                    else
                    {
                        string val = await content.ReadAsStringAsync();
                        dic.Add(content.Headers.ContentDisposition.Name, val);
                    }
                }
                return apiResult;
            }
            catch (System.Exception e)
            {
                return apiResult;
            }
        }

解析FormData方式二

[HttpPost,Route("PostFormData")]
        public async Task PostFormData()
        {
            ApiResult apiResult = new ApiResult();
            // Check if the request contains multipart/form-data.
            // 检查该请求是否含有multipart/form-data
            if (!Request.Content.IsMimeMultipartContent())
            {
                //throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                apiResult.code = 415;
            }
            string root =System.Web.HttpContext.Current.Server.MapPath("~/App_Data"); 
var provider = new MultipartFormDataStreamProvider(root);          
            try
            {                
                // Read the form data.
                // 读取表单数据
                await Request.Content.ReadAsMultipartAsync(provider);
                //获取表单数据
                foreach (var key in provider.FormData.AllKeys)
                {
                    foreach (var val in provider.FormData.GetValues(key))
                    {
                        string formDate = string.Format("{0}: {1}", key, val);
                    }
                }
                //获取表单文件
                foreach (MultipartFileData file in provider.FileData)
                {
                    string fileName = file.Headers.ContentDisposition.FileName;
                    string localFileName = file.LocalFileName;
                }
                return apiResult;
            }
            catch (System.Exception e)
            {
                return apiResult;
            }
        }

解析FormData方式一与方式二的区别在于 方式一中的文件的保存更灵活,方式二在读取FormData的数据时,会自动将文件保存在root路径下,最后读取的localFileName为文件的存储路径

注:返回的结果集ApiResult是我自己定义的,这个返回结果可根据自己的需要定义

你可能感兴趣的:(.Net,webApi,C#,fileUpload)