web文件上传(三)--webapi后台接收参数和文件

今儿查了好多关于webapi接收前台同时传来的参数和文件,这一通查找啊,把谷歌百度都翻烂了,找了一堆乱七八糟的,和大家分享下。


好多人们是这样做的

        public async Task<HttpResponseMessage> PostFormData()
        {
            // Check if the request contains multipart/form-data.  
            // 检查该请求是否含有multipart/form-data  
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            string root = 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))
                    {
                        //Trace.WriteLine(string.Format("{0}: {1}", key, val));
                    }
                }
                // This illustrates how to get the file names.  
                // 以下描述如何获取文件名  
                foreach (MultipartFileData file in provider.FileData)
                {
                    Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                    Trace.WriteLine("Server file path: " + file.LocalFileName);
                }
                return Request.CreateResponse(HttpStatusCode.OK);
            }
            catch (System.Exception e)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }

这让我一通看才看明白,而且上面还是整理完他们代码过后的

后来自己找到了比较好的方法,如下

public IHttpActionResult getTest2()
        {

            string id=HttpContext.Current.Request["id"];
            string name = HttpContext.Current.Request["name"];
            HttpFileCollection files = HttpContext.Current.Request.Files;

            foreach (string key in files.AllKeys)
            {
                HttpPostedFile file = files[key];//file.ContentLength文件长度
                if (string.IsNullOrEmpty(file.FileName) == false)
                    file.SaveAs(HttpContext.Current.Server.MapPath("~/App_Data/") + file.FileName);
            }

            return Ok("success2");
        }
简单明了,共享之,希望对大家有帮助。


评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值