웹쟁이의 일상

[ASP.NET MVC] Dropzone js를 이용한 파일 업로드 본문

C#

[ASP.NET MVC] Dropzone js를 이용한 파일 업로드

jellyChoi 2019. 5. 10. 13:29

오늘은 ASP.NET MVC에서 Dropzone js를 이용해 파일 업로드를 하는 방법을 알아 보겠습니다.

 

Dropzone js는 비동기 방식으로 파일을 업로드 하기 쉽게 하기 위한 플러그인입니다.

 

대중적이고 널리 쓰이고 있기 때문에 자료를 찾기에도 용이합니다.

 

public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));
           
            // Script 추가 시 여기에 Include - Build 필요 //
            bundles.Add(new ScriptBundle("~/bundles/Import").Include(
                "~/js/dropzone.js",
               ));
               
               // CSS 추가 시 여기에 Include - Build 필요 //
            bundles.Add(new StyleBundle("~/Content/css").Include(
               "~/css/dropzone.css"
            ));
        }
    }

BundleConfig에 dropzone.js와 dropzone.css를 추가해줍니다.

 

번들에 추가하기 싫으시면 스크립트에 직접 추가하셔도 됩니다.

<form action="#" class="dropzone" id="dropzone" enctype="multipart/form-data">
</form>
.dropzone {
        background: white;
        border-radius: 5px;
        border: 2px dashed rgb(0, 135, 247);
        border-image: none;
        min-weight:300px;
        min-width: 500px;
        margin-left: auto;
        margin-right: auto;
    }

html 파일 업로드 영역을 추가하고 싶은 곳에 위의 코드를 작성해주시고 css로 꾸며줍니다.

.dropzone .dz-default.dz-message {
  opacity: 1;
  -ms-filter: none;
  filter: none;
  -webkit-transition: opacity 0.3s ease-in-out;
  -moz-transition: opacity 0.3s ease-in-out;
  -o-transition: opacity 0.3s ease-in-out;
  -ms-transition: opacity 0.3s ease-in-out;
  transition: opacity 0.3s ease-in-out;
  background-image: url("images/fileupload.png");
  background-repeat: no-repeat;
  background-position: 0 0;
  position: absolute;
  width: 150px;
  height: 100px;
  margin-left: -54px;
  margin-top: -50px;
  top: 50%;
  left: 50%;
}

더 상세하게 꾸며보고싶다면 dropzone.css를 직접 커스텀할 수 있습니다.

 

저는 background-image를 기본 이미지에서 제가 바꾸고 싶은 이미지로 바꿔주었습니다.

$('.dropzone').dropzone({
            url: setAjaxUrl('/fileUpload'), // 드롭다운 시 업로드 되는 URL
            addRemoveLinks: true,
            maxFilesize: 300, // 드롭다운 시 파일 크기
            init: function () {
                this.on('success', function (file, json) {
                    // 파일이 서버에 업로드가 완료 되었 을때
                    if (res.msg == 'OK') {
                        //만약에 response message 가 OK 라면
                        alert("업로드가 완료 되었습니다.");
                    } else {
                        // 만약에 OK 가 아니라면???
                        alert("업로드가 실패하였습니다.");
                    }
                    
                });

                this.on('addedfile', function (file) {
                    $("#file-dropzone").hide();
                    $(".upload-progress").show();
                });

                this.on('drop', function (file) {
                    // 파일이 드롭되면Upload Progress 나와줘야 된다.
                    $("#file-dropzone").hide();
                    $(".upload-progress").show();
                });

                // 2개 이상의 파일을 올릴 시 이전에 올린 이미지 삭제.
                this.on("maxfilesexceeded", function (file) {
                    this.removeAllFiles();
                    this.addFile(file);
                });
            }
        });

비동기통신을 진행할 스크립트를 작성해 주겠습니다.

 

public JsonResult fileUpload()
        {
            bool isSavedSuccessfully = true;
            string fName = "";
            try
            {
                foreach (string fileName in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[fileName];
                    //Save file content goes here
                    fName = file.FileName;
                    if (file != null && file.ContentLength > 0)
                    {
                        var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\WallImages", Server.MapPath(@"\")));
                        string pathString = Path.Combine(originalDirectory.ToString(), "D:\\webProject\\image");
                        var fileName1 = Path.GetFileName(file.FileName);
                        bool isExists = Directory.Exists(pathString);
                        if (!isExists)
                            Directory.CreateDirectory(pathString);
                        var path = string.Format("{0}\\{1}", pathString, file.FileName);
                        file.SaveAs(path);
                    }
                }
            }
            catch (Exception)
            {
                isSavedSuccessfully = false;
            }

            if (isSavedSuccessfully)
            {
                return Json(new { msg = "OK" });
            }
            else
            {
                return Json(new { msg = "Error in saving file" });
            }
        }

 

이제 컨트롤러에서 파일 업로드를 처리해줄 로직을 만들어 주겠습니다.

 

pathString에 경로를 넣어주겠습니다. 코드 블럭에 이상이 생겼나 색깔이 이상하네요.

 

여기까지 하시면 완성입니다.

 

파일을 드래그 앤 드랍 하시거나 dropzone 영역을 클릭하시고 파일을 올리면 지정한 경로에 파일이 업로드 되는걸 

보실 수 있습니다.

'C#' 카테고리의 다른 글

비주얼 스튜디오(Visual studio) 2019 설치 방법  (0) 2019.05.01
Comments