【问题标题】:How to send data and image together through ajax json in asp.net mvc [duplicate]如何在asp.net mvc中通过ajax json一起发送数据和图像[重复]
【发布时间】:2017-08-11 19:23:43
【问题描述】:

以前,我只需要创建一个表单,其中只包含要发送到动作的数据而不是图像,现在,我遇到了将数据与图像一起发布到动作的要求。我不知道如何将图像附加到数据中,以便我可以让它继续工作。

这就是我将数据和图像一起发布的方式,但我收到null 的实际操作:

HTML

<input type="file" id="profilePic" name="file" value="Browse">
<input type="text" id="EmployeeCode" name="EmployeeCode" value="EmployeeCode">
<input type="text" id="SystemCode" name="SystemCode" value="SystemCode">
<input type="button" value="Create" onclick="SaveEmpData()" />

我知道如何获取输入类型的文本数据并通过ajax请求以json格式发送并将其保存到数据库,但是当涉及到通过ajax请求以json格式获取数据和图像时,我'不知道如何做到这一点。

JS

var empdata = { "SystemCode": "", "EmployeeCode": "" };

empdata.EmployeeCode = $("#EmployeeCode").val();
empdata.SystemCode = $("#SystemCode").val();

var data = new FormData();
var files = $("#profilePic").get(0).files;    
data.append("Image", files[0]); 

Ajax

$.ajax({
    url: '/EmployeeMasterA/Create',
    headers: headers,
    data: JSON.stringify({ employeeMasterA: empdata, profilePic: data }),
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    traditional: true,
    success: function (result) {

        if (result.Success == "1") {
            window.location.href = "/EmployeeMasterA/Index";
        }
        else {
            alert(result.ex);
        }
    }
});

Create 行动:

[HttpPost]
public ActionResult Create([Bind(Include = "SystemCode,EmployeeCode")] EmployeeMasterA employeeMasterA, HttpPostedFileBase profilePic)
{            
    var pic = System.Web.HttpContext.Current.Request.Files["Image"];
}

在上面的代码中,pic 变量是null。我的问题是:

从表单中获取数据+图像并通过 ajax 请求将其发送到操作的正确方法是什么?任何帮助都深表感谢:)

更新

在参考了liran的回答后,我尝试通过这种方式编辑我的代码进行绑定:

JS

var empbind = { "profilePic" : "", "employeeMasterA" : "" };
// Created empdata and data (image) object as mentioned above
empbind.employeeMasterA = empdata;
empbind.profilePic = data;
var empbindjson = JSON.stringify(empbind);

并更改了 Ajax data 参数如下:

$.ajax({
   .
   .
   data: empbindjson,
   .
   .
});

并更改了我的控制器操作:

[HttpPost]
public ActionResult Create([Bind(Include = "employeeMasterA,profilePic")]       EmployeeBind bind)
{            
    var pic = System.Web.HttpContext.Current.Request.Files["Image"];
}

employeeMasterA,profilePic 在上述代码的调试模式下都收到null,这是我的新绑定类:

public class EmployeeBind
{
    public EmployeeMasterA employeeMasterA { get; set; }
    public HttpPostedFileBase profilePic { get; set; }
}

好的,现在,我已更改代码以将其与profilePic 绑定,我做错了什么吗?因为create actionbind 参数都包含employeeMasterA 和profilePic 的null。

【问题讨论】:

  • 您需要使用FormData 并设置正确的ajax 选项。

标签: jquery json ajax asp.net-mvc image-uploading


【解决方案1】:

尝试改变一些需要工作的东西:

  $('#save').click(function () {

    var form = $("#yourForm");
    var data = new FormData();
    var files = $("#profilePic").get(0).files;
    data.append("Image", files[0]);
    $.each(form.serializeArray(), function (key, input) {
        data.append(input.name, input.value);
    });

  $.ajax({
      url: '/EmployeeMasterA/Create',
      data: data,
      type: 'POST',
      processData: false,
      contentType: false,
      success: function (result) {

          if (result.Success == "1") {
              window.location.href = "/EmployeeMasterA/Index";
          }
          else {
              alert(result.ex);
          }
      }
  });
});

在 HTML 中:

 <form id="yourForm">
    <input type="file" id="profilePic" name="file" value="Browse">
    <input type="text" id="EmployeeCode" name="EmployeeCode" value="EmployeeCode">
    <input type="text" id="SystemCode" name="SystemCode" value="SystemCode">
    <input type="button" value="Create" onclick="SaveEmpData()" id="save">
</form>

编辑:如果仍然无法正常工作,请将 EmployeeMasterA 和 HttpPostedFileBase 绑定到同一个类,例如:

    [HttpPost]
    public ActionResult Create([Bind(Include = "SystemCode,EmployeeCode")] VMNewClass bind)
    {            
        var pic = System.Web.HttpContext.Current.Request.Files["Image"];
    }


public class VMNewClass{

 public EmployeeMasterA employeeMasterA {get;set;}
 public  HttpPostedFileBase profilePic {get;set;}

}

如果你不想这样做:

 $.each(form.serializeArray(), function (key, input) {
        data.append(input.name, input.value);
    });

你可以写:

var data = new FormData();
    var files = $("#profilePic").get(0).files;
    data.append("profilePic", files[0]);
    data.append("EmployeeCode", $("#EmployeeCode").val());
    data.append("SystemCode", $("#SystemCode").val());

如果我在评论中附加了文章,请编辑

 <script>
        var empdata = { "SystemCode": "", "EmployeeCode": "" };

        empdata.EmployeeCode = $("#EmployeeCode").val();
        empdata.SystemCode = $("#SystemCode").val();

        var data = new FormData();
        var files = $("#profilePic").get(0).files;
        data.append("Image", files[0]);
        data.append("EmployeeCode", $("#EmployeeCode").val());
        data.append("SystemCode", $("#SystemCode").val());

        $.ajax({
            url: '/EmployeeMasterA/Create',
            data: data,
            type: 'POST',
            contentType: false, // Not to set any content header  
            processData: false, // Not to process data  
            success: function (result) {

                if (result.Success == "1") {
                }
                else {
                    alert(result.ex);
                }
            }
        });

</script>

控制器:

[HttpPost]
public ActionResult Create([Bind(Include = "SystemCode,EmployeeCode")] EmployeeMasterA employeeMasterA)
{            
    HttpPostedFileBase profilePic = Request.Files[0]; // your file
}

【讨论】:

  • 我不想做 form.serialize() 因为我有一个巨大的表单,其中包含一对多关系中的大量数据,所以,为了简单起见,我只是添加了两个文本框字段EmployeeCode, SystemCode 而不是所有 260 个字段。现在,我以某种方式设法创建了所有这 260 个字段的 json 对象,即empdata,我无法更改此empdata 对象,因为,如果只关注empdata,它工作正常,我只想添加一个empdata 中的更多内容,即profilePic,我应该如何将profilePic 附加到empdata,或者有什么不同的方式可以通过profilePic 而不会打扰empdata
  • 请参考我更新的问题。
  • 是的,我明白了,所以 myabe 使用 Request.Files File Upload 我用我为你附上的文章编辑我的答案,如果仍然不能帮助你,我希望其他人可以帮助你美好的一天:)跨度>
  • 在第一个答案中我添加到 ajax processData: false, contentType: false 我检查了我的代码并且它正在工作(第二个答案也对我有用)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-03
  • 1970-01-01
  • 2015-11-21
  • 2014-01-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多