我不知道我做错了什么,但出于某种原因,HttpPostedFileBase总是返回空。当我试图在服务器端上传一个文件时,我继续使用HttpPosterFileBase获得空:下面是我的代码:
<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 });
}
}发布于 2015-09-16 18:41:30
使用FormData.append将所有参数添加到请求的post正文中。
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);
}
});https://stackoverflow.com/questions/32616171
复制相似问题