심재운 블로그

728x90
반응형

ASP.NET MVC 와 JQUERY 의 progressbar 를 통해 첨부파일 로딩바 구현하기

 

ASP.NET MVC 와 JQUERY 의 progressbar 를 통해 첨부파일을 AJAX 을 통해 업로드 로딩화면 코드 입니다.

 

 

ASP.NET MVC 의 controller 에서 ActionResult 함수를 통해 첨부파일을 받아서 첨부파일의 이름을 반환합니다.

 

public ActionResult UploadFiles()
        {
            string FileName="";
            HttpFileCollectionBase files = Request.Files;
            for (int i = 0; i < files.Count; i++)
            {
                //string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";  
                //string filename = Path.GetFileName(Request.Files[i].FileName);  

                HttpPostedFileBase file = files[i];
                string fname;

                // Checking for Internet Explorer  
                if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
                {
                    string[] testfiles = file.FileName.Split(new char[] { '\\' });
                    fname = testfiles[testfiles.Length - 1];
                }
                else
                {
                    fname = file.FileName;
                    FileName = file.FileName;
                }

                // Get the complete folder path and store the file inside it.  
                fname = Path.Combine(Server.MapPath("~/Uploads/"), fname);
                file.SaveAs(fname);
            }
            return Json(FileName, JsonRequestBehavior.AllowGet);
        }

 

front 단의 소스인데, progressbar 함수를 사용하기 위해서는 jquery 와 jquery-ui.css, jquery-ui.js 파일이 필요합니다.

var fileData = new FormData();  를 통해 첨부파일 정보를 담아, ajax 의 data 속성에 담아 post 로 전송을 합니다.

 

@{
    ViewBag.Title = "Home Page";
}
<link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
    rel="stylesheet">
<link href="../../Content/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="../../Content/bootstrap-theme.css" rel="stylesheet" type="text/css" />
<style>
    .ui-widget-header
    {
        background: #cedc98;
        border: 1px solid #DDDDDD;
        color: #333333;
        font-weight: bold;
    }
    .progress-label
    {
        position: absolute;
        left: 50%;
        top: 13px;
        font-weight: bold;
        text-shadow: 1px 1px 0 #fff;
    }
    .red
    {
        color: red;
    }
</style>
<div class="container">
    <h1>
        File Upload Demo</h1>
    <div id="FileBrowse">
        <div class="row">
            <div class="col-sm-4">
                <input type="file" id="Files" />
            </div>
            <div class="col-sm-2">
                <input type="button" id="UploadBtn" class="btn btn-danger" value="Upload" />
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-sm-4">
            <div id="progressbar-5">
                <div class="progress-label">
                </div>
            </div>
        </div>
    </div>
    <br />
    <div class="row">
        <div class="col-sm-6">
            <table class="table" id="ListofFiles">
                <tr>
                    <th>
                        Files
                    </th>
                    <th>
                        Action
                    </th>
                </tr>
            </table>
        </div>
    </div>
    <br />
    <br />
    <br />
    <br />
</div>
@section scripts{
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
    <script>
        $('#UploadBtn').click(function () {

            var fileUpload = $("#Files").get(0);
            var files = fileUpload.files;
            // Create FormData object  
            var fileData = new FormData();
            // Looping over all files and add it to FormData object  
            for (var i = 0; i < files.length; i++) {
                fileData.append(files[i].name, files[i]);
            }
            $.ajax({
                url: '/Home/UploadFiles',
                type: "POST",
                contentType: false, // Not to set any content header  
                processData: false, // Not to process data  
                data: fileData,
                async: false,
                success: function (result) {
                    if (result != "") {
                        $('#FileBrowse').find("*").prop("disabled", true);
                        LoadProgressBar(result);
                    }
                },
                error: function (err) {
                    alert(err.statusText);
                }
            });

        });

        function LoadProgressBar(result) {
            var progressbar = $("#progressbar-5");
            var progressLabel = $(".progress-label");
            progressbar.show();
            $("#progressbar-5").progressbar({
                //value: false,
                change: function () {
                    progressLabel.text(
                     progressbar.progressbar("value") + "%");
                },
                complete: function () {
                    progressLabel.text("Loading Completed!");
                    progressbar.progressbar("value", 0);
                    progressLabel.text("");
                    progressbar.hide();
                    var markup = "<tr><td>" + result + "</td><td><a href='#' onclick='DeleteFile(\"" + result + "\")'><span class='glyphicon glyphicon-remove red'></span></a></td></tr>";
                    $("#ListofFiles tbody").append(markup);
                    $('#Files').val('');
                    $('#FileBrowse').find("*").prop("disabled", false);
                }
            });
            function progress() {
                var val = progressbar.progressbar("value") || 0;
                progressbar.progressbar("value", val + 1);
                if (val < 99) {
                    setTimeout(progress, 25);
                }
            }
            setTimeout(progress, 100);
        }
   
    </script>
}

 

jquery 의 progressbar 에 대한 설명은 아래 사이트를 참고하면 됩니다.

www.tutorialspoint.com/jqueryui/jqueryui_progressbar.htm

 

JqueryUI - Progressbar - Tutorialspoint

JqueryUI - Progressbar Progress bars indicate the completion percentage of an operation or process. We can categorize progress bar as determinate progress bar and indeterminate progress bar. Determinate progress bar should only be used in situations where

www.tutorialspoint.com

www.c-sharpcorner.com/article/file-upload-with-jquery-progress-bar-in-asp-mvc/

 

File Upload With JQuery Progress Bar In ASP MVC

First we have to create an Asp Mvc project in visual studio. To do that, Open Visual Studio -> New Project -> A new dialog window will appear -> In left pane select C# ->select Web -> Select "ASP.NET MVC 4 Application" name your project and click ok.

www.c-sharpcorner.com

 

Index.cshtml
0.00MB
HomeController.cs
0.00MB

728x90
반응형

공유하기

facebook twitter kakaoTalk kakaostory naver band

본문과 관련 있는 내용으로 댓글을 남겨주시면 감사하겠습니다.

비밀글모드

loading