.Net WebApi接收上传文件

前端通过ContentType:multipart/form-data,上传文件到后端,后端接收并处理请求

前端用Postman发起请求示例:

后端Action代码:

        [HttpPost]
        public HttpResponseMessage UploadFile()
        {
            try
            {
                UploadFileRQVM rqvm = new UploadFileRQVM();

                #region 请求参数校验
                HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];// 获取传统 context
                HttpRequestBase request = context.Request;// 定义传统 request 对象
                rqvm.UserName = request.Form["UserName"];
                rqvm.Age= request.Form["Age"].ToInt();#endregion

                #region 上传文件
                HttpFileCollection files = HttpContext.Current.Request.Files;
                HttpPostedFile file = null;
                if (files == null || files.Count <= 0)
                {
                    return Error("上传文件内容有误");
                }

                file = files[0];

                var fs = file.InputStream;
                var fileByte = new byte[fs.Length];
                fs.Read(fileByte, 0, fileByte.Length);
                fs.Close();
                #endregion

                #region 上传文件处理
                var saveFileRPVM = SaveFileHelper();
                if (saveFileRPVM.type != 1)
                {
                    return Error(saveFileRPVM.message);
                }
                var uploadFile = saveFileRPVM.resultdata;
                if (uploadFile == null)
                {
                    return Error("文件处理异常");
                }
                #endregion

                return Success("操作成功", uploadFile);
            }
            catch (Exception ex)
            {
                return Error("请求异常,异常原因" + ex.Message);
            }

        }

 

posted on 2020-08-13 16:32  CeleryCabbage  阅读(3314)  评论(1编辑  收藏  举报

导航