需求:上传学员信息时同时上传头像信息,学员基本信息表和科目表为一对多关系表(添加基本信息后添加通过科目信息)。
测试:
[HttpPost] public string Post() { if (!Request.Content.IsMimeMultipartContent()) throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "Invalid Request!")); //获取学员信息 Student model = new Student() { Name = HttpContext.Current.Request.Form["StuName"], GroupName = HttpContext.Current.Request.Form["GroupName"], // ... }; //获取学员通过科目名称 string passSubject = HttpContext.Current.Request.Form["passSubject"]; //获取学员未通过科目名称 string noPassSubject = HttpContext.Current.Request.Form["noPassSubject"]; Trace.WriteLine("begin 添加学员信息"); //添加学员信息 stuService.AddStuByAsync(model).ContinueWith(p => { long stuId = p.Result; Trace.WriteLine("begin 通过科目表"); subjectService.AddPassSubject(passSubject, stuId);//添加此学员通过科目信息 Trace.WriteLine("end 通过科目表"); Trace.WriteLine("begin 未通过科目表"); subjectService.AddPassSubject(noPassSubject, stuId);//添加此学员未通过科目信息 Trace.WriteLine("end 未通过科目表"); }); Trace.WriteLine("end 添加学员信息"); string path = System.Web.HttpContext.Current.Server.MapPath("~/Images/upload/"); Trace.WriteLine("获取图片......"); Request.Content.ReadAsMultipartAsync().ContinueWith(p => { var content = p.Result.Contents; Trace.WriteLine("begin 图片"); foreach (var item in content) { if (string.IsNullOrEmpty(item.Headers.ContentDisposition.FileName)) { continue; } item.ReadAsStreamAsync().ContinueWith(a => { Stream stream = a.Result; string fileName = item.Headers.ContentDisposition.FileName; fileName = fileName.Substring(1, fileName.Length - 2); Trace.WriteLine("图片名称:"+fileName); //stream 转为 image saveImg(path, stream, fileName); }); } Trace.WriteLine("end 图片"); }); return "ok"; }
表单测试:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> </head> <body> <form enctype="multipart/form-data" method="post" action="http://localhost:17822/api/Student/Post"> <p><label>学员名称:</label> <input name="StuName" /></p> <p><label>分组名称</label><input name="GroupName" /></p> <p><label>通过科目:</label> <input name="passSubject" /></p> <p><label>未通过科目:</label> <input name="noPassSubject" /></p> <p><label>头像</label> <input type="file" name="dfile" /></p> <p><label></label> <input type="submit" /></p> </form> </body> </html>
提交后结果如下:
通过输出 "图片名称” 在 "end 图片" 下可以看出,图片在上传时主线程已经继续向下执行了
上部分也是同样,在方法 AddStuByAsync() 执行完的时候启动子线程去添加科目信息。