【问题标题】:asp.net mvc 4 AJAX File Upload file is NULLasp.net mvc 4 AJAX文件上传文件为NULL
【发布时间】:2017-01-17 13:54:52
【问题描述】:

/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");
    }

【问题讨论】:

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


【解决方案1】:

您不能使用 AJAX 上传文件。这是不支持的。如果您想这样做,您可以使用一些文件上传插件,例如 Uploadify 或 Blueimp File Upload,或者如果客户端浏览器支持,则使用 HTML 5 File API。

【讨论】:

    猜你喜欢
    • 2012-07-27
    • 2011-02-16
    • 2016-05-04
    • 1970-01-01
    • 2011-06-22
    • 1970-01-01
    • 2013-12-23
    • 2012-12-22
    • 2011-01-26
    相关资源
    最近更新 更多