Asp.Net MVC4系列---基礎篇(5)

mybwu_com發表於2014-03-29

Asynchronous File Upload in MVC



1. Script reference :



<script type="text/javascript" src="../MvcFileUploadDemo/Scripts/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="../MvcFileUploadDemo/Scripts/handlebars.min.js"></script>
<script type="text/javascript" src="../MvcFileUploadDemo/Scripts/linq.min.js"></script>

<script src="http://malsup.github.com/jquery.form.js"></script>



add latest jquery .
handlebars : a jquery lib for easier js template handling
linq.js: a js lib make collections operation easier and better , just like c# linq.
jquery.form.js : a open source jquery lib , providing method do sync form post .


2.HTML :



@using (Ajax.BeginForm("Upload", "FileUploadDemo", 
    new AjaxOptions() { HttpMethod = "POST" }, new {id="frmUploadFile"}))
{
    <label for="file1">Filename:</label>
    <input type="file" name="files" id="file1" />


    <label for="file2">Filename:</label>
    <input type="file" name="files" id="file2" />
    


    <input type="hidden" id="hdnCurrentPathUpload" value="@Model.CurrentPath" name="currentPath"/>
    
    <input type="submit" value="Upload" id="btnUploadSubmit" />
}


<div class="progress">
    <div class="bar"></div >
    <div class="percent"></div >
</div>


<div id="status"></div>




3.Script :



 (function () {
        var bar = $('.bar');
        var percent = $('.percent');
        var status = $('#status');


        $('#frmUploadFile').ajaxForm({
            beforeSend: function () {
                status.empty();
             
                var percentVal = '0%';
                bar.width(percentVal);
                percent.html(percentVal);
            },
            uploadProgress: function (event, position, total, percentComplete) {
                var percentVal = percentComplete + '%';
                bar.width(percentVal);
                percent.html(percentVal);
            },
            success: function () {
                var percentVal = '100%';
                bar.width(percentVal);
                percent.html(percentVal);
            },
            complete: function (xhr) {
               // status.html(xhr.responseText);
            }
        });
    })();


4.Controller


 [HttpPost]
        public ContentResult Upload()
        {
            var files = Request.Files;
            if (files != null)
            {
                
                for (int i = 0; i < files.Count; i++)
                {
                    var file = files[i];
                    if (file == null) continue;


                    var pic = "/"+ Path.GetFileName(file.FileName);
                    var path = CombinePath(
                                           MapPath(Constant.BaseDir + Request.Form["currentPath"]), pic);
                    // file is uploaded
                    file.SaveAs(path);
		}
	    }


	  return "uploaded successfully.";


	}





相關文章