通过Ajax在ASP.NET MVC3中上传文件无法正常工作

时间:2012-04-16 12:31:07

标签: asp.net-mvc-3 forms jquery

我已经在mvc3中正常提交了一个文件。现在我需要对Ajax做同样的事情。所以我使用了这个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'方法中的file参数始终为null。似乎无法使其工作。另外,我们可以使用'Ajax.BeginForm()'帮助器吗?

4 个答案:

答案 0 :(得分:1)

AFAIK,您不能通过ajax上传文件...发布文件需要完整的回发。

你需要一个闪存解决方案或类似的东西才能实现它。 例如,使用UPLOADIFY ...

See this blog post to make it work

答案 1 :(得分:1)

<input><form> html元素的名称属性用于在提交表单后引用表单数据。

注意:只有具有name属性的表单元素才会在提交表单时传递其值。

由于操作方法public ActionResult TakeFile(HttpPostedFileBase file){..}具有参数名称'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" />
}

答案 2 :(得分:0)

尝试使用以下

<input type="file" id="file" name = "attachment"/>

在控制器内添加以下代码以获取文件对象

var file = Request.Files["attachment"];

答案 3 :(得分:0)

上传文件时,您的选项中的dataType:json似乎很奇怪,您是否尝试删除它?

同时尝试使用输入类型为

Name属性
<input type="file" id="file" name="file" />