文件上传不工作
我已经提交了MVC3文件normally.Now我需要做Ajax.So我用这个jQuery插件一样:http://jquery.malsup.com/form/#ajaxSubmit文件上传不工作
查看代码:
$(document).ready(function() {
var options = {
url: "/Home/TakeFile",
dataType: "json",
success: showResponse
};
$("#File").submit(function() {
alert("submit");
$(this).ajaxSubmit(options);
return false;
});
});
function showResponse(responseText, statusText, xhr, $form) {
alert("showResponse");
alert(responseText.fileName);
}
</script>
@using (Html.BeginForm("TakeFile", "Home", FormMethod.Post, new { @id = "File", enctype = "multipart/form-data" }))
{
<input type="file" id="file" />
<input type="submit" value="Click to submit" id="button" />
}
控制器代码:
[HttpPost]
public ActionResult TakeFile(HttpPostedFileBase file)
{
return Json(new { fileName=file.FileName});
}
在我的 'TakeFile' 方法的文件参数总是null.Can't似乎得到它working.Also,它使用“的Ajax我们可以做.BeginForm()'helper?
的名称一个<form>
内的<input>
html元素的属性使用的形式被提交之后,以引用的表单数据。
注意:只有具有name属性的表单元素在提交表单时才会传递其值。
由于动作方法public ActionResult TakeFile(HttpPostedFileBase file){..}
有一个参数名称'文件',在该视图中,文件输入元素应该具有name='file'
属性。更新代码:
@using (Html.BeginForm("TakeFile", "Home", FormMethod.Post, new { @id = "File", enctype = "multipart/form-data" }))
{
<input type="file" id="file" name="file" />
<input type="submit" value="Click to submit" id="button" />
}
谢谢..这是唯一的缺陷..错过了输入类型的名称属性! – 2012-04-17 06:36:46
尝试使用如下
<input type="file" id="file" name = "attachment"/>
控制器内添加以下代码获取文件对象
var file = Request.Files["attachment"];
都能跟得上回一个响应。 ..var文件为空。 – 2012-04-16 12:39:06
这是因为您也在发送Ajax请求。停止Ajax请求并再试一次,这应该是可行的,因为我在 – Jayanga 2012-04-17 02:49:24
的dataType:json
在您选择上传文件时似乎很奇怪,你有没有尝试删除它?
也可以尝试使用Name
属性与输入型
<input type="file" id="file" name="file" />
之前使用过这段代码。实际上,'datatype'告诉你从服务器获得的响应类型,而不是请求的响应类型。 – 2012-04-16 15:17:03
是的,这是真的。我只是看到表单的id与输入类型的id相同.. – 2012-04-16 15:22:04
Oh..yeah ...将更改任何一个id并查看 – 2012-04-16 15:25:58
文件只是不上传...否则它会在控制器适当的方法,还我可以给它被正确接收的“showResponse方法()” – 2012-04-16 14:07:26