0

/file/uploadfile/I'm trying to implement uploading file to servere, when user clicks OK in Select files dialog. Trying to implement such demo: http://jsfiddle.net/cHpDa/ . But in controller i recieve NULL instead of file. I've read that i need to ajaxify my form (HttpPostedFile in File Upload process is NULL if I use AJAX) but my attempts to implement ajaxify were failed.

View:

<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>

Controller:

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

        return PartialView("FileList");
    }
Community
  • 1
  • 1
CatCap
  • 240
  • 5
  • 19

1 Answers1

0

You cannot upload files using AJAX. This is not supported. If you want to do that you could either use some file upload plugin such as Uploadify or Blueimp File Upload or use the HTML 5 File API if the client browser supports it.