WebApi上传文件

WebApi上传文件

#region 上传文件
        /// <summary>
        /// 通过multipart/form-data方式上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<HttpResponseMessage> PostFile()
        {
            MessagesDataCodeModel json = new MessagesDataCodeModel(false, "无效参数", 401);

            try
            {
                // 是否请求包含multipart/form-data。
                if (!Request.Content.IsMimeMultipartContent())
                {
                    logger.Error("上传格式不是multipart/form-data");
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }

                string root = HttpContext.Current.Server.MapPath("/UploadFiles/");
                if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/UploadFiles/")))
                {
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/UploadFiles/"));
                }

                var provider = new MultipartFormDataStreamProvider(root);

                StringBuilder sb = new StringBuilder(); // Holds the response body

                // 阅读表格数据并返回一个异步任务.
                await Request.Content.ReadAsMultipartAsync(provider);

                // 如何上传文件到文件名.
                foreach (var file in provider.FileData)
                {
                    string orfilename = file.Headers.ContentDisposition.FileName.TrimStart('"').TrimEnd('"');
                    FileInfo fileinfo = new FileInfo(file.LocalFileName);
                    //sb.Append(string.Format("Uploaded file: {0} ({1} bytes)
", fileInfo.Name, fileInfo.Length));
                    //最大文件大小 
                    //int maxSize = Convert.ToInt32(SettingConfig.MaxSize);
                    if (fileinfo.Length <= 0)
                    {
                        json.Success = false;
                        json.Msg = "请选择上传文件";
                        json.Code = 301;
                    }
                    else if (fileinfo.Length > ConfigHelper.MaxFileSize)
                    {
                        json.Msg = "上传文件大小超过限制";
                        json.Code = 302;
                    }
                    else
                    {
                        string fileExt = orfilename.Substring(orfilename.LastIndexOf('.'));
                        //定义允许上传的文件扩展名 
                        //String fileTypes = SettingConfig.FileTypes;
                        //if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
                        //{
                        //    json.Msg = "图片类型不正确";
                        //    json.Code = 303;
                        //}
                        //else
                        //{
                        //String ymd = DateTime.Now.ToString("yyyyMMdd", System.Globalization.DateTimeFormatInfo.InvariantInfo);
                        //String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", System.Globalization.DateTimeFormatInfo.InvariantInfo);

                        fileinfo.CopyTo(Path.Combine(root, fileinfo.Name + fileExt), true);
                        json.Success = true;
                        json.Msg = "操作成功";
                        json.Code = 200;
                        sb.Append("/UploadFiles/" + fileinfo.Name + fileExt);
                        json.Data = sb.ToString();
                        //}
                    }
                    fileinfo.Delete();//删除原文件
                }
            }
            catch (System.Exception e)
            {
                json.Success = false;
                json.Msg = "服务器无响应";
                json.Code = 500;
                logger.Error("PostFile()服务器错误", e);
            }
            return ToJsonTran.ToJson(json);
        }
        #endregion 上传文件

  

原文地址:https://www.cnblogs.com/xsj1989/p/5533400.html