재우니의 블로그


비동기처럼 로딩화면을 만들어 보기 위해 jquery.form.js 스크립트를 사용해 보죠.

<h2>Async File Upload</h2>

@using (Ajax.BeginForm("AsyncUpload", "Home", new AjaxOptions() { HttpMethod = "POST" }, 
    new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    <input type="file" name="files" id="fu1" />
    <input type="submit" value="Upload File" />

}

<div class="progress">
    <div class="progress-bar">0%</div>
</div>
<div id="status"></div>
<style>
    .progress {
        position: relative;
        width: 400px;
        border: 1px solid #ddd;
        padding: 1px;
    }

    .progress-bar {
        width: 0px;
        height: 20px;
        background-color: #57be65;
    }
</style>
@section scripts{
    <script src="http://malsup.github.com/jquery.form.js"></script>
    <script>
        (function () {
            var bar = $('.progress-bar');
            var percent = $('.progress-bar');
            var status = $('#status');

            $('form').ajaxForm({
                beforeSend: function () {
                    status.empty();
                    var percentValue = '0%';
                    bar.width(percentValue);
                    percent.html(percentValue);
                },
                uploadProgress: function (event, position, total, percentComplete) {
                    var percentValue = percentComplete + '%';
                    bar.width(percentValue);
                    percent.html(percentValue);
                },
                success: function (d) {
                    var percentValue = '100%';
                    bar.width(percentValue);
                    percent.html(percentValue);
                    $('#fu1').val('');
                    alert(d);
                },
                complete: function (xhr) {
                    status.html(xhr.responseText);
                }
            });
        })();
    </script>
}


controller 에서 이를 처리하는데, 사실 보면 동기로 처리함..

[HttpPost] [ValidateAntiForgeryToken] public ActionResult AsyncUpload(IEnumerable<HttpPostedFileBase> files) { int count = 0; if (files != null) { foreach (var file in files) { if (file != null && file.ContentLength > 0) { var fileName = Guid.NewGuid() + Path.GetExtension(file.FileName); var path = Path.Combine(Server.MapPath("~/FileData"), fileName); file.SaveAs(path); count++; } } } return new JsonResult { Data = "업로드 완료!! " + count + " file(s) 업로드됨." }; }