将带有数据和文件的JSON发布到Web Api – jQuery / MVC

我需要用一个请求发送到带有JSON(最好)的Api控制器。

问题是传递数据和文件(图像上传)。 我的财产空了(null)。

我看了很多博客,但似乎无法通过图像传递数据。

public class SomeModel { public string Name { get; set; } public string Email { get; set; } public string City { get; set; } public HttpPostedFileBase Image { get; set; } public string Title { get; set; } public string Description { get; set; } public string CountryCode { get; set; } } [HttpPost] public void CreateContestEntry(SomeModel model) { // model.Image is always null // .. get image here - the other properties no issues } 

jQuery的

  // create model for controller var model = { Name: $.trim($contestForm.find('[name="nombre"]').val()) + ' ' + $.trim($contestForm.find('[name="apellido"]').val()), Email: $.trim($contestForm.find('[name="email"]').val().toLowerCase()), City: $.trim($contestForm.find('[name="cuidad"]').val()), Title: $.trim($contestForm.find('[name="title"]').val()), Description: $.trim($contestForm.find('[name="description"]').val()), CountryCode: 'co', Image: $contestForm.find('[name="file-es"]')[0].files[0] // this has the file for sure }; $.ajax({ url: '/Umbraco/api/ControllerName/CreateContestEntry', type: 'POST', dataType: 'json', data: JSON.stringify(model), //data: $('#test-form').serialize(), // tried this and using FormData() processData: false, async: false, contentType: 'application/json; charset=utf-8', complete: function (data) { }, error: function (response) { console.log(response.responseText); } }); 

在此处输入图像描述

我看过的博客:

  • 使用添加个人表单数据从MVC上传到Web Api的文件
  • http://www.asp.net/web-api/overview/advanced/sending-html-form-data,-part-1
  • http://www.asp.net/web-api/overview/advanced/sending-html-form-data,-part-2
  • 自定义表单数据与多个文件到Web API控制器

当我尝试FormData$('#form1').serialize()方法时,我的provider.FileDataprovider.FormData也总是空的。 我从方法中删除了model参数,当我将其切换时,断点正在点击。

  [HttpPost] public void CreateContestEntry() { string root = HttpContext.Current.Server.MapPath("~/App_Data"); var provider = new MultipartFormDataStreamProvider(root); try { // Read the form data. Request.Content.ReadAsMultipartAsync(provider); // This illustrates how to get the file names. foreach (MultipartFileData file in provider.FileData) { // empty } foreach (var key in provider.FormData.AllKeys) { foreach (var val in provider.FormData.GetValues(key)) { // empty } } //return Request.CreateResponse(HttpStatusCode.OK); } catch(Exception ex) { } } 

解:

关于@Musa的答案,这是Api控制器代码。 我将NameValueCollection映射到我的模型。

  [HttpPost] public void CreateContestEntry() { try { // get variables first NameValueCollection nvc = HttpContext.Current.Request.Form; var model = new WAR2015ContestModel(); // iterate through and map to strongly typed model foreach (string kvp in nvc.AllKeys) { PropertyInfo pi = model.GetType().GetProperty(kvp, BindingFlags.Public | BindingFlags.Instance); if (pi != null) { pi.SetValue(model, nvc[kvp], null); } } model.Image = HttpContext.Current.Request.Files["Image"]; } catch(Exception ex) { } } 

您无法使用JSON上传文件(即任意二进制数据),因为JSON是文本格式。 你将不得不使用多部分表单数据。

 // create model for controller var model = new FormData(); model.append('Name', $.trim($contestForm.find('[name="nombre"]').val()) + ' ' + $.trim($contestForm.find('[name="apellido"]').val())); model.append('Email', $.trim($contestForm.find('[name="email"]').val().toLowerCase())); model.append('City', $.trim($contestForm.find('[name="cuidad"]').val())); model.append('Title', $.trim($contestForm.find('[name="title"]').val())); model.append('Description', $.trim($contestForm.find('[name="description"]').val())); model.append('CountryCode', 'co'); model.append('Image', $contestForm.find('[name="file-es"]')[0].files[0]); // this has the file for sure $.ajax({ url: '/Umbraco/api/ControllerName/CreateContestEntry', type: 'POST', dataType: 'json', data: model, processData: false, contentType: false,// not json complete: function (data) { var mediaId = $.parseJSON(data.responseText); //? }, error: function (response) { console.log(response.responseText); } });