WebApi form-data上传文件

来源:互联网 发布:淘宝账号能改名吗 编辑:程序博客网 时间:2024/06/01 17:01
  ///<summary>
        /// 上传附件信息 ""
        ///MsgJson:json数组,格式如下[{},{},{}]
        ///MsgJson中的json对象中下列参数是必须的:BUSTABLENAME(业务表名),BUSTABLEKEYID(业务表主键Id),FILENAME(文件名),
        ///FILETYPE(文件类型),FILEPATH(附件保存路径)
        ///一下参数可在json中拓展
        /// 文件名称与json数组中FileNme一一对应
        /// </summary>
        /// <returns></returns>
        public async Task<BaseResult> UploadFileLotNew()
        {
            string log = "进入上传接口";
            if (Request.Properties.ContainsKey("MS_HttpContext"))
            {
                log = log + "--含有MS_HttpContext";
                dynamic ctx = Request.Properties["MS_HttpContext"];
                if (ctx != null)
                {
                    log = log + "--ctx不为空";
                    string c = ctx.Request.Headers["Content-Type"];
                    log = log + "--Content-Type:" + c;
                }
                else
                {
                    log = log + "--ctx为空";
                }
            }
            else
            {
                log = log + "--不含有MS_HttpContext";
            }
            DBLog.debug("开始进入文件上传接口_UploadFileLotNew" + log, 2, null);
            BaseResult br = new BaseResult();
            IList<Tf_Bas_Attachment> attachList = new List<Tf_Bas_Attachment>();
            //IsMultipartContent方法检查该请求是否含有多部分MIME消息。如果不是,控制器返回HTTP状态码415(不支持的媒体类型)。
            if (!Request.Content.IsMimeMultipartContent())
            {
                br.state = false;
                br.message = "上传失败,非multipart(多部分)MIME消息的格式";
                return br;
            }
            Dictionary<string, string> dic = new Dictionary<string, string>();
            string webFolder = GetWbePath();
            string savaFolder = GetSavePath(webFolder);
            if (!Directory.Exists(savaFolder))
            {
                Directory.CreateDirectory(savaFolder);
            }
            // 设置上传目录 
            //var provider = new MultipartFormDataStreamProvider(savaFolder);//原写法
            var provider = new RenamingMultipartFormDataStreamProvider(savaFolder);//重命名写法
            try
            {
                // Read the form data.读取表单数据
                //异步方法。为了在该方法完成之后执行一些工作,需要使用“continuation(继续)任务”(.NET 4.0)或await关键字(.NET 4.5)
                //这里执行文件存储========
                DBLog.debug("文件上传接口_UploadFileLotNew--开始文件存储", 2, null);
                await Request.Content.ReadAsMultipartAsync(provider);
                DBLog.debug("文件上传接口_UploadFileLotNew--结束文件存储", 2, null);
                //存储完成================




                #region  处理json


                //string userId = provider.FormData.Get("UserId");
                //string DataTypeId = provider.FormData.Get("DataTypeId");
                //if (String.IsNullOrEmpty(userId))
                //{
                //    br.state = false;
                //    br.message = "数据有误,请检查UserId";
                //    return br;
                //}
                //switch (DataTypeId)
                //{
                //    case "1":
                //        break;
                //    case "2":
                //        break;
                //    default:
                //        br.state = false;
                //        br.message = "数据有误,请检查DataTypeId";
                //        return br;


                //}
                List<UploadCheckFileJsonModel> list = new List<UploadCheckFileJsonModel>();
                string json = provider.FormData.Get("MsgJson");
                if (String.IsNullOrEmpty(json))
                {
                    br.state = false;
                    br.message = "MsgJson不能为空";
                    return br;
                }
                //DBLog.debug("文件上传接口_UploadFileLotNew:" + "userId:" + userId + "MsgJson:" + json, 2, null);
                try
                {
                    list = JsonConvert.DeserializeObject<List<UploadCheckFileJsonModel>>(json);




                }
                catch (Exception e)
                {
                    br.state = false;
                    br.message = "数据有误,请检查MsgJson";
                    return br;
                }


                #endregion


                #region json 与图片一一对应
                foreach (MultipartFileData file in provider.FileData)
                {
                    string filePath = file.Headers.ContentDisposition.FileName;
                    if (filePath.StartsWith(@"""") && filePath.EndsWith(@""""))
                        filePath = filePath.Substring(1, filePath.Length - 2);
                    string fileName = Path.GetFileName(filePath);
                    string extName = Path.GetExtension(fileName);
                    FileInfo fileInfo = new FileInfo(file.LocalFileName);
                    string fileNewName = fileInfo.Name;
                    File.AppendAllText(HttpContext.Current.Server.MapPath("~/log.txt"), fileNewName + "\r\n");
                    
                    UploadCheckFileJsonModel _model = list.Find(


                           delegate(UploadCheckFileJsonModel model)
                           {
                               return model.FILENAME == fileName;
                           });
                    if (_model == null)
                    {
                        br.state = false;
                        br.message = "数据有误,MsgJson与文件不匹配";
                        return br;
                    }
                    if (String.IsNullOrEmpty(_model.BUSTABLENAME) || String.IsNullOrEmpty(_model.BUSTABLEKEYID))
                    {
                        br.state = false;
                        br.message = "数据有误,缺少必要参数";
                        return br;
                    }


                    Tf_Bas_Attachment _entity = new Tf_Bas_Attachment();


                    _entity.ID = Guid.NewGuid().ToString();
                    _entity.BUSTABLENAME = _model.BUSTABLENAME;
                    _entity.BUSTABLEKEYID = _model.BUSTABLEKEYID;
                    _entity.FILENAME = fileName;
                    _entity.FILETYPE = extName;
                    _entity.FILEPATH = webFolder + "/" + fileNewName;
                    _entity.CREATETIME = System.DateTime.Now.ToString();
                    attachList.Add(_entity);
                    string originalPath = HttpContext.Current.Server.MapPath(_entity.FILEPATH);
                    string thumbPath = GetThumbnailUrl(_entity.FILEPATH);
                    thumbPath = HttpContext.Current.Server.MapPath(thumbPath);
                    ImageHelper.MakeZoomImage(originalPath, thumbPath, 100, 100, "HW");
                }
                #endregion




            }
            catch (Exception e)
            {
                DBLog.debug("文件上传接口_UploadFileLotNew:catch:" + e.Message, 2, e);
                br.message = "上传失败,异常信息:" + e.Message;
                br.state = false;
                return br;
            }
            if (iTF_GOV_GOVERNANCETASK_Business.InsertList(attachList))
            {
                br.state = true;
                br.message = "上传成功";
                br.jdata = attachList;
                return br;
            }
            else
            {
                br.state = false;
                br.message = "上传失败,数据库存储出错";
                return br;
            }


        }


  /// <summary>
        /// 重命名上传的文件
        /// </summary>
        public class RenamingMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
        {
            public string Root { get; set; }
            //public Func<FileUpload.PostedFile, string> OnGetLocalFileName { get; set; }


            public RenamingMultipartFormDataStreamProvider(string root)
                : base(root)
            {
                Root = root;
                Console.Write(this.FormData.Get("MsgJson"));
            }
            /// <summary>
            /// 获取新的文件名,时间格式
            /// </summary>
            /// <param name="headers"></param>
            /// <returns></returns>
            public override string GetLocalFileName(HttpContentHeaders headers)
            {
                string filePath = headers.ContentDisposition.FileName;


                // Multipart requests with the file name seem to always include quotes.
                if (filePath.StartsWith(@"""") && filePath.EndsWith(@""""))
                    filePath = filePath.Substring(1, filePath.Length - 2);
                var filename = Path.GetFileName(filePath);
                string extName = Path.GetExtension(filename);
                string fileNewName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + extName;
                var extension = Path.GetExtension(filePath);
                string contentType = null;
                if (headers.ContentType != null)
                {
                    contentType = headers.ContentType.MediaType;
                }


                return fileNewName;
            }




        }