HttpPostedFileBase返回null

时间:2015-09-16 18:35:59

标签: javascript forms

我无法弄清楚我做错了什么但由于某种原因HttpPostedFileBase总是返回null。当我尝试在服务器端上传文件时,我继续使用HttpPosterFileBase获取null:这是我的代码:

<form method="POST" id="frmNote" action="/Client/SaveNote"  enctype="multipart/form data>
Date:  @Html.TextBox("StratDate", note.StratDate)
Note: @Html.TextArea("note note.ClientNote)
 <input type="file" name="file" id="file" />
 <input type="submit" value="Save" class="button" />
</form>



<script type="text/javascript">
$("#frmNote").submit(function (event) {
        event.preventDefault();
  var formData = new FormData($('form')[0]);
  formData.append("file", $('input[type=file]')[0].files[0]);
            formData += "& StratDate =" + $("#StratDate").val();
            formData += "& Note =" + $("# Note ").val();
  $.ajax({
                type: "POST",
                url: "/Client/SaveNote",
                data: formData,
                contentType: false,
                processData: false,
                success: function() {
                    alert("note saved successfully.");
                },
                error: function() {
                    alert(result.message);
                }
            });
    });
</script>



[HttpPost]
[ValidateInput(false)]
        public JsonResult SaveNote(ActivityData note)
        {

            try
            {
                HttpPostedFileBase file = Request.Files[0];
if (file == null)
 {

fileName = Path.GetFileName(file.FileName);
filePath = Path.Combine(Server.MapPath("~/image"), fileName);
   file.SaveAs(filePath);

}
                client.SaveNote(note);
                 return Json(new { error = false });
            }

            catch (Exception ex)
            {
                return Json(new { error = true, message = ex.Message }); 
 }
}

1 个答案:

答案 0 :(得分:0)

使用FormData.append将所有参数添加到请求的帖子正文中。

formData.append("file", $('input[type=file]')[0].files[0]);
formData.append("StratDate", $("#StratDate").val());
formData.append("Note",  $("#Note").val());

由于您使用包含要传递的所有数据的表单调用FormData构造函数,因此您不需要向其添加任何内容。

var formData = new FormData($('form')[0]);    
$.ajax({
            type: "POST",
            url: "/Client/SaveNote",
            data: formData,
            contentType: false,
            processData: false,
            success: function() {
                alert("note saved successfully.");
            },
            error: function() {
                alert(result.message);
            }
});