为什么我的ajax没有发送在控制器端上传的图像?

时间:2016-08-10 06:18:08

标签: javascript jquery ajax asp.net-mvc

我正在使用jquery ajax将模型与图像一起发送到我的控制器。 这是我的表格。

  @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "CreateUser" ,enctype = "multipart/form-data" } ))
        {

            @Html.AntiForgeryToken();
              @Html.ValidationSummary(true)
               <fieldset>
               <div class="row">
                    <div class="col-xs-6">
                        @*----FIRST NAME----*@
                        <label>
                            First Name <span class="text-red font12">*</span>
                        </label>
                        @Html.TextBoxFor(model => model.FirstName, new { @class = "form-control", id = "txtFirstName", @maxlength = "30" })
                    </div>


                    <div class="col-xs-6">
                        @*----LAST NAME----*@
                        <label>
                            Last Name <span class="text-red font12">*</span>
                        </label>

                        @Html.TextBoxFor(model => model.LastName, new { @class = "form-control", id = "txtLastName", @maxlength = "30" })
                    </div>

               <div class="col-xs-6">
                        @*----Logo Upload----*@

                        <label>
                           Logo Uploaad <span class="text-red font12">*</span>
                        </label>
                        <div class="input-group">


                            <input type="file" id="FileUpload1" />

                        </div>

                    </div>
                </div>

        <div class="row">
                    <div class="col-xs-4" style="float:right;">
                        <input type="button" value="Save" class="btn btn-primary btn-block btn-flat" onclick="validateandcreate();" />
                    </div>
                </div>

} 这是我的jquery代码

function CreateUser() {

    var username = $("#txtUserName").val();

    var fileUpload = $("#FileUpload1").get(0);
    var files = fileUpload.files;

    var fileData = new FormData();  

    // Looping over all files and add it to FormData object  
    for (var i = 0; i < files.length; i++) {  
        fileData.append(files[i].name, files[i]);  
    }  


    debugger;
    if (username != "") {

        var model = {
            "FirstName": encodeURIComponent($("#txtFirstName").val()),
            "LastName": encodeURIComponent($("#txtLastName").val())
        };


        $.ajax({
            url: '/User/Create',
            method: 'post',
            dataType: 'json',
            data: { m: model, f: fileData },
            success: function (data) {
              alert("success");
            },
            error: function (err) {

               alert("error");
            }
        });
    }
}

如果我只发送模型,它可以正常工作,但如果我发送上传的图像,它就不会打到控制器。 这是我的控制者。

   [HttpPost]
    //[AuthorizationFilter]
   [ValidateAntiForgeryToken]
    public JsonResult Create(Models.Users user, HttpPostedFileBase file_Uploader)
    {
   //code
    }

1 个答案:

答案 0 :(得分:1)

您需要在ajax上设置processData: falsecontentType: false,以便通过jQuery.ajax()提交文件

您还可以将文件以外的数据添加到FormData

var formdata = new FormData();
formdata.append("file", fileobject);
formdata.append("model", JSON.stringify({
  name: "Johny",
  lastname: "Good"
}));

$.ajax({
  url: '/User/Create',
  method: 'post',
  dataType: 'json',
  contentType: false,
  processData: false,
  data: formdata,
  success: function(data) {
    alert("success");
  },
  error: function(err) {

    alert("error");
  }
});

请参阅Ajax File Uploads