2016. 1. 16. 15:00

요즘 'Html5'를 활용하여 드래그 앤 드롭(Drag and Drop)을 이용하여 파일 업로드를 하고 있습니다.

우리도 구현해 봅시다~

그냥 'Html5'만 사용하는 건 아니고 제이쿼리(jquery)도 사용합니다.

 

 

참고 : codeguru - Uploading Files Using HTML5 Drag-and-Drop and ASP.NET

 

 

1. HTML 페이지 작성하기

프로젝트를 생성하고 'FlieUpload.aspx'를 추가합니다.

 

1-1. html 작성

바디에 'div'로 드래그 앤 드롭 영역을 만들고 아래 버튼을 하나 만듭니다.

<body>
<form id="form1" runat="server">
	<div>
		<div id="box">Drag & Drop files from your machine on this box.</div>
		<br />
		<button id="upload" type="button">Upload Selected Files</button>
	</div>
</form>
</body>

 

 

1-2. CSS 작성

스타일시트는 만든 드래그 앤 드롭 영역을 꾸미기 위해 사용합니다.

#box {
        width:300px;
        height:100px;
        text-align:center;
        vertical-align:middle;
        border:2px solid #ff6a00;
        background-color:#ffd800;
        padding:15px;
        font-family:Arial;
        font-size:16px;
        margin-top:35px;
      }

 

 

1-3. 자바스크립트 작성

제이쿼리를 임포트하고 그 밑에 다음 스크립트를 넣습니다.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<script type="text/javascript">
    var selectedFiles;

    $(document).ready(function () {
        if (!Modernizr.draganddrop) {
            alert("This browser doesn't support File API and Drag & Drop features of HTML5!");
            return;
        }

        var box;
        box = document.getElementById("box");
        box.addEventListener("dragenter", OnDragEnter, false);
        box.addEventListener("dragover", OnDragOver, false);
        box.addEventListener("drop", OnDrop, false);

        $("#upload").click(function () {
            var data = new FormData();
            for (var i = 0; i < selectedFiles.length; i++) {
            data.append(selectedFiles[i].name, selectedFiles[i]);
            }
            $.ajax({
            type: "POST",
            //비하인드 호출 핸들러 주소
            url: "FileUpload.ashx",
            contentType: false,
            processData: false,
            data: data,
            success: function (result) {
                alert(result);
            },
            error: function () {
                alert("There was error uploading files!");
            }
            });
        });
    });

    function OnDragEnter(e) {
    e.stopPropagation();
    e.preventDefault();
    }

    function OnDragOver(e) {
    e.stopPropagation();
    e.preventDefault();
    }

    function OnDrop(e) {
    e.stopPropagation();
    e.preventDefault();
    selectedFiles = e.dataTransfer.files;
    $("#box").text(selectedFiles.length + " file(s) selected for uploading!");
    }
</script>

 

 

2. 비하인드 코드 작성

비하인드 코드는 제네릭 처리기(generic handler, *.ashx )를 이용하여 작성합니다.

제네릭 처리기는 간단하게 설명하면 연결된 UI가 없는 .aspx라고 보시면 됩니다.

 

프로젝트에 '제네릭 처리기'를 추가합니다.

이때 이름은 자바스크립트에서 입력했던 이름으로 추가해야 합니다.

(우리는 'FileUpload.ashx'로 되어 있습니다.)

 

 

코드를 다음과 같이 작성합니다.

public class FileUpload : IHttpHandler
{

	public void ProcessRequest(HttpContext context)
	{
		if (context.Request.Files.Count > 0)
		{
			HttpFileCollection files = context.Request.Files;
			foreach (string key in files)
			{
				HttpPostedFile file = files[key];
				string fileName = file.FileName;
				fileName = context.Server.MapPath("~/uploads/" + fileName);
				file.SaveAs(fileName);
			}
		}

		context.Response.ContentType = "text/plain";
		context.Response.Write("Hello World");
	}

	public bool IsReusable
	{
		get
		{
			return false;
		}
	}
}

 

 

3. 폴더 생성

이제 실행한 후 노란박스안에 파일을 올려봅시다.

 

 

업로드 버튼을 누르면 에러가 뽱~

 

 

경로가 없다는 에러이니 'uploads'폴더가 없어서 나는 에러임을 알 수 있습니다.

'uploads'폴더를 만든 후 다시 시도해 봅시다.

 

 

마무리

찾은 참고 자료가 너무 잘 동작해서 사실 제가 덧 붙인게  없다시피 합니다 ㅎㅎㅎ

 

그래도 프로젝트 샘플은 있어야겠죠?

FlieUpload_Html5.zip
다운로드