asp.net mvc 4 AJAX文件上传文件为NULL

时间:2014-02-05 10:36:22

标签: jquery ajax asp.net-mvc asp.net-mvc-4

/ file / uploadfile /当我在“选择文件”对话框中单击“确定”时,我正在尝试实施上传文件。试图实现这样的演示:http://jsfiddle.net/cHpDa/。但在控制器中我收到NULL而不是文件。我已经读过我需要ajaxify我的表单(HttpPostedFile in File Upload process is NULL if I use AJAX),但我尝试实现ajaxify失败了。

查看:

<script src="@Url.Content("~/Scripts/jquery-1.8.2.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/modernizr-2.6.2.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.form.js")" type="text/javascript"></script>

<h1>Ajax File Upload Demo</h1>
<form id="myForm" method="post" enctype="multipart/form-data">
    <input type="file" size="60" name="myfile" id="myfile" />
</form>

<div id="progress">
    <div id="bar"></div>
    <div id="percent">0.0%</div >
</div>
<div id="message"></div>


<div id="FilesListDiv">
    @Html.Partial("~/Views/File/FileList.cshtml")
</div>

<script>
    $('#myfile').on("change",function(){
        var options = {
            type:"post",
            url: "/file/uploadfile/",
            beforeSend: function()
            {
                $("#progress").show();
                //clear everything
                $("#bar").width('0%');
                $("#message").html("");
                $("#percent").html("0%");
            },
            uploadProgress: function(event, position, total, percentComplete)
            {
                $("#bar").width(percentComplete+'%');
                $("#percent").html(percentComplete+'%');
            },
            success: function()
            {
                $("#bar").width('100%');
                $("#percent").html('100%');

            },
            complete: function(response)
            {
                $("#message").html("<font color='green'>"+response.responseText+"</font>");
            },
            error: function()
            {
                $("#message").html("<font color='red'> ERROR: unable to upload files</font>");
            }
        };

        $("#myForm").ajaxSubmit(options);
    });
</script>

控制器:

    [HttpPost]
    public ActionResult UploadFile(HttpPostedFileBase myfile)
    {
        if (myfile != null) //here is a PROBLEM - myfile is NULL
        {
           this.UploadFile(myfile);
        }

        return PartialView("FileList");
    }

1 个答案:

答案 0 :(得分:0)

您无法使用AJAX上传文件。这不受支持。如果你想这样做,你可以使用一些文件上传插件,如Uploadify或Blueimp文件上传,或者如果客户端浏览器支持它,则使用HTML 5 File API。