WebAPI接口 上传文件资源

1.API接口 异步请求
[System.Web.Http.AcceptVerbs("GET", "POST")] [HttpPost] public Task<Business> PostReport() { Business bussiness = new Business(); // 检查是否是 multipart/form-data if (!Request.Content.IsMimeMultipartContent("form-data")) { Business business = new Business(); business.message = 0; business.messageDetail = "数据形式错误"; } //文件保存目录路径 上传图片 string url = Request.RequestUri.Host; string SaveTempPath = "/Content/images/ReportImg/"; String dirTempPath = HttpContext.Current.Server.MapPath(SaveTempPath); if (!Directory.Exists(dirTempPath)) Directory.CreateDirectory(dirTempPath);//如果目录不存在怎新建 // 设置上传目录 var provider = new MultipartFormDataStreamProvider(dirTempPath); List<string> imgList = new List<string>();//图片路径 var task = Request.Content.ReadAsMultipartAsync(provider). ContinueWith<Business>(o => { foreach (MultipartFileData file in provider.FileData) { string orfilename = file.Headers.ContentDisposition.FileName.TrimStart('"').TrimEnd('"'); FileInfo fileinfo = new FileInfo(file.LocalFileName); //最大文件大小 int maxSize = 10000000; if (fileinfo.Length <= 0) { bussiness.message = 0; bussiness.messageDetail = "请选择上传文件。"; } else if (fileinfo.Length > maxSize) { bussiness.message = 0; bussiness.messageDetail = "上传文件大小超过限制。"; } else { string fileExt = orfilename.Substring(orfilename.LastIndexOf('.')); //定义允许上传的文件扩展名 String fileTypes = "gif,jpg,jpeg,png,bmp"; if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1) { bussiness.message = 0; bussiness.messageDetail = "上传文件扩展名是不允许的扩展名。"; } else { String ymd = DateTime.Now.ToString("yyyyMMdd", System.Globalization.DateTimeFormatInfo.InvariantInfo); //String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", System.Globalization.DateTimeFormatInfo.InvariantInfo); string newFileName = Guid.NewGuid().ToString(); fileinfo.CopyTo(Path.Combine(dirTempPath, newFileName + fileExt), true); fileinfo.Delete(); bussiness.message = 1; bussiness.messageDetail = "上传成功。"; imgList.Add(SaveTempPath + newFileName + fileExt); } } if (bussiness.message == 0) return bussiness; } // 读取项目参数并保存 if (provider.FormData != null && provider.FormData.Count > 0) { #region 读取请求参数 Dictionary<string, string> dic = new Dictionary<string, string>(); foreach (var key in provider.FormData.AllKeys) { foreach (var val in provider.FormData.GetValues(key)) { dic.Add(key, val); } } #endregion } return bussiness; }); return task; } #endregion
2.后台调用方法
  using (var client = new HttpClient())
            {
                using (var content = new MultipartFormDataContent())
                {
                    // Make sure to change API address

                    client.BaseAddress = new Uri("http://192.168.1.87:8082/");
                    //client.BaseAddress = new Uri("https://localhost:44301/");
                    // Add first file content
                    var fileContent1 = new ByteArrayContent(File.ReadAllBytes(@"C:\Users\admim\Desktop\js\images\bci.jpg"));

                    fileContent1.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = "bci1.jpg"
                    };
                    // Add Second file content

                    var fileContent2 = new ByteArrayContent(File.ReadAllBytes(@"C:\Users\admim\Desktop\js\images\bci.jpg"));

                    fileContent2.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = "bci2.jpg"

                    };
content.Add(fileContent1);

                    content.Add(fileContent2);
                    //content.Add(fileContent3);
                    //content.Add(fileContent4);
                    //content.Add(fileContent5);

                    //content.Add(fileContent3);
                    // Make a call to Web API

                    #region请求字段值
                    content.Add(new StringContent("4"), "FCoachProjectID");
或者 
      HttpContent httpContentLogin = new StringContent("{\"name\":10005005,\"password\":\"aaaa\"}");
                    httpContentLogin.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    var result = client.PostAsync("/api/TeacherCoach/PostReport", content).Result;
                   

 

 

 

posted @ 2017-08-04 17:38  独孤小天天  阅读(820)  评论(0编辑  收藏  举报