【问题标题】:Upload JSON and HttpPostedFile to MVC via jQuery Ajax [duplicate]通过 jQuery Ajax 将 JSON 和 HttpPostedFile 上传到 MVC [重复]
【发布时间】:2016-01-09 17:07:09
【问题描述】:

在这种情况下,我如何将<input type="file" id="uploadStudent" /> 上传的文件发布到 mvc 控制器?

Javascript

$.ajax({
  url: "/Home/CompleteAttendeeType",
  contentType: "application/json;charset=utf-8",
  dataType: "JSON",
  type: "POST",
  data: JSON.stringify({
    //PostedFile: "I AM CONFUSED HOW TO UPLOAD?",
    AttendeeType: 1,
    LicenseNumber: $("#txtLicenseNumber").val(),
    LicenseState: $("#txtLicenseState").val(),
    SchoolName: $("#txtSchoolName").val(),
    SchoolLocation: $("#txtSchoolLocation").val()
  })
})

MVC

[HttpPost]
public JsonResult CompleteAttendeeType(CompleteAttendeeTypeRequest request)
{
  return Json(string.Empty, JsonRequestBehavior.AllowGet);
}

public enum AttendeeType
{
  Professional,
    Student,
    Owner,
    Guest
}

public class CompleteAttendeeTypeRequest
{
  public HttpPostedFile PostedFile { get; set; }
  public AttendeeType AttendeeType { get; set; }

  public string LicenseNumber { get; set; }
  public string LicenseState { get; set; }

  public string SchoolName { get; set; }
  public string SchoolLocation { get; set; }
}

【问题讨论】:

  • 您可以使用FormData。示例参考this answer
  • @StephenMuecke — 不会提供 JSON 输出
  • @Quentin,不知道你在说什么。 OP 可以序列化表单或单独添加每个属性 - 例如formdata.append(LicenseNumber, $("#txtLicenseNumber").val()); 等将绑定到控制器中的 CompleteAttendeeTypeRequest 模型。
  • @StephenMuecke — 请求被格式化为 application/json 而不是 multipart/form-data。您无法从 FormData 对象中获取 application/json。
  • OP 想要上传文件和属性,以便它们可以绑定到模型。它不需要是 JSON 输出 - 但它确实需要工作,这就是链接答案的作用:)

标签: javascript jquery json ajax asp.net-mvc-5


【解决方案1】:

首先使用File API to read the contents of the file

然后你需要以可以用 JSON 表示的格式来表达数据。如果数据是字符串,那么您可以使用它。否则,您将需要转换它。 Converting it to base64 是一种方法。

然后,您将拥有一个变量中的数据,该变量可以包含在您传递给JSON.stringify 的对象中。

如果您将其编码为 base64,则需要decode it on the server

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-25
    • 2013-11-24
    • 2015-01-12
    • 2019-10-20
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多