同时上传参数及图片到 Web Api
方法一:利用 FormData
JS:
function uploadFileAndParam() { var url = "http://localhost:42561/api/upload/UploadPost"; /* FormData 对象就是模拟一个Form表单格式的数据,以二进制的方式提交,等同于 Form 表单 设置 enctype="multipart/form-data". 由于 ajax 请求默认 contentType:"application/x-www-form-urlencoded" (这也是 Form 表单 enctype 的默认值) 所以需要设置 contentType: false processData: false */ var data = new FormData($("#myForm")[0]);//参数是JS对象,而 $("#myForm") 是JQ对象,并且是数组,所以需要加[0] data.append("sex", 1);//追加数据 data.delete("name");//删除数据 var id = data.get("id");//获取数据 //还有 has(),getAll(),forEach() 等方法. $.ajax({ url: url, data: data, type: "post", cache: false,//不缓存,暂时不明白为什么 FormData 对象提交,都要设置这个 contentType: false,//告诉JQ, 不要设置 ContentType 请求头 processData: false,//告诉JQ, 不要处理发送的数据 success: function () { } }); }
HTML:
<div> <span>测试同时Post参数及文件</span><br /> <form action="http://localhost:42561/api/upload/UploadPost" method="post" id="myForm"> <input type="text" name="id" value="11" /> <input type="text" name="name" value="中1&1文" /> <input type="text" name="age" value="22" /> <input type="file" name="myFile" /> <input type="submit" value="submit提交" /> <input type="button" value="button提交" onclick="uploadFileAndParam()" /> </form> </div>
方法二:原生Form表单提交
<form id="myForm6" enctype="multipart/form-data" method="post" action="http://*****"> <input type="text" name="id" value="35" /> <input type="text" name="name" value="wjire" /> <input type="file" name="myFile" /> <input type="submit" value="submit提交" /> </form>
后台 Web Api 接收
public async Task<HttpResponseMessage> UploadPost() { var request = HttpContext.Current.Request; var id = request.Form["id"]; var name = request.Form["name"]; var age = request.Form["age"]; var files = HttpContext.Current.Request.Files; var path = HttpContext.Current.Server.MapPath("/img/"); if (files.Count > 0) { foreach (string file in files) { var img = files[file]; if (img?.ContentLength > 0) { var fileName = img.FileName; await Task.Run(() => img.SaveAs(path + fileName)); } } return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("成功@!!!!!") }; } else { var stream = request.InputStream; if (stream.Length > 0) { var bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); } } return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "没有文件"); }