webapi 上传图片

需求:上传学员信息时同时上传头像信息,学员基本信息表和科目表为一对多关系表(添加基本信息后添加通过科目信息)。

测试:

        [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() 执行完的时候启动子线程去添加科目信息。

时间: 2024-08-03 19:29:20

webapi 上传图片的相关文章

kindeditor扩展粘贴图片功能&amp;修改图片上传路径并通过webapi上传图片到图片服务器

前言 kindeditor是一个非常好用的富文本编辑器,它的简单使用我就不再介绍了. 而kindeditor却对图片的处理不够理想. 本篇博文需要解决的问题有两个: kindeditor扩展粘贴图片功能 kindeditor修改图片上传路径并通过webapi上传图片到图片服务器(支持分布式图片) 结果演示 1.扩展粘贴图片功能演示 2.修改图片上传路径演示: 我们的网站演示地址是:http://localhost:9393/ 我们的图片服务器地址是:http://localhost:9394/

WebApi上传图片 await关键字

await关键字对于方法执行的影响 将上一篇WebApi上传图片中代码修改(使用了await关键字)如下: [HttpPost] public async Task<string> Post() { if (!Request.Content.IsMimeMultipartContent()) throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "Invalid Req

WebClient和HttpClient, 以及webapi上传图片

httppost请求. applicationkey/x-www-form-urlencoded 请求: Email=321a&Name=kkfew webapi里面, 如果用实体, 能接受到. 因为这是一个属性一个属性去匹配的原因 application/json 请求:{Email:321a  ,  Name:kkfew} 如果接收参数为dynamic, 则没有问题. 因为直接把json对象转化成dynamic对象了 using (WebClient webclient = new WebC

.Net Core WebApi上传图片的两种方式

我这边主要是为了上传图片,话不多说,上代码. 方式一:通过Form表单上传 后端: /// <summary> /// 上传图片,通过Form表单提交 /// </summary> /// <returns></returns> [Route("Upload/FormImg")] [HttpPost] public ActionResult UploadImg(List<IFormFile> files) { if (file

记录一个简单webapi 上传图片

图片转base64字符串,到接口后,再转回保存.代码里面是转成byte[]之后转的,也可以用base64字符串直接转图片. 只想记录一下简单的流程. 1,服务端 保存图片业务代码: public class UpLoadFile    {        public string UpLoad(string fileName,string filePath,byte[] fileData)        {            Bitmap map =BitmapFromBytes(fileD

Net实现上传图片按比例自动缩小或放大的方法

本文实例主要展示了.Net实现上传图片按比例自动缩小或放大的方法,是非常实用的功能.分享给大家供大家参考之用.具体方法如下: net实现裁剪网站上传图片的方法 .net中 发送邮件内容嵌入图片的具体实例 vb.net借助剪贴板将图片导入excel内 asp.net图片上传实例 ASP.net WebAPI 上传图片实例 .Net下二进制形式的文件(图片)的存储与读取详细解析 Asp.net图片上传实现预览效果的简单代码 asp.net上传图片并作处理水印与缩略图的实例代码 asp.net 图片超

Asp.Net MVC上传图片

mvc上传图片 [HttpPost] public JsonResult Upload() { if (Request.Files.Count > 0) { if (Request.Files.Count == 1) { HttpPostedFileBase file = Request.Files[0]; if (file.ContentLength > 0) { string title = string.Empty; title = DateTime.Now.ToString("

Aspose.Cells导入导出

插件:Aspose.Cells 没有安装office插件也能使用: 导出:不能使用ajax异步· /// <summary> /// 导出试题 /// </summary> /// <param name="userId">用户Id</param> /// <param name="courseId">课程Id</param> /// <returns></returns>

Ionic app 上传图片之webApi接口

App上传图片对应的webApi服务端是怎么处理的呢? using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web;