[Spring] Drag and Drop file 업로드

dh·2022년 11월 22일
0

구디샵 프로젝트

목록 보기
5/5

이전에 했던 file input에 Drag and Drop을 이용하여 파일 업로드 기능을 추가하려고 합니다.

https://www.w3schools.com/html/html5_draganddrop.asp
http://www.tcpschool.com/html/html5_api_dragAndDrop

ondragover 속성

ondragover 속성은 드래그되는 대상 객체가 어느 요소 위에 놓일 수 있는지를 설정합니다.
기본적으로 HTML 요소는 다른 요소의 위에 위치할 수 없습니다.
따라서 다른 요소 위에 위치할 수 있도록 만들기 위해서는 놓일 장소에 있는 요소의 기본 동작을 막아야만 합니다.
이 작업을 event.preventDefault() 메소드를 호출하는 것만으로 간단히 설정할 수 있습니다.
drop에서 event.preventDefault()하지 않으면 이미지파일이 새창에서 열리고, 파일은 다운로드되는데 기본적인 브라우저에서 실행되는 기능인것 같습니다.

코드

<div class="file_drag" id="file_drag">
	<div id="plz_drag">파일을 마우스로 끌어 오세요</div>
    <div class="file_list_header" style="display: none;">
    	<div class="file_list_header_task">
    		<button type="button" id="removeAll_button"><span class="blind">X</span></button>
    	</div>
    	<div class="file_list_header_title"><span class="text">파일명</span></div>
    	<div class="file_list_header_volume"><span class="text">총용량 </span><span id="fileSize">0</span></div>
	</div>

	<ul id="fileList"></ul>
</div>

file_drag div에 dragover, drop 이벤트를 줍니다.
drop을 할때 이벤트에서 발생한 dataTransfer의 FileList를 <ul id="fileList"></ul>안에 리스트를 추가해 보여주고 drop이벤트의 dataTransfer를 우리가 직접만든 dataTransfer에 추가해주고 이것을 다시 input file의 files로 옮겼습니다.

const file_drag = document.getElementById("file_drag")

file_drag.addEventListener("dragover",function(e){
    console.log("드래그 오버")
    e.preventDefault();
})
file_drag.addEventListener("drop",function(e){
    console.log("드랍")
    e.preventDefault();
    
    arr= event.dataTransfer.files;
    addFileList(arr)
    for(var i=0; i<arr.length; i++){
       dataTransfer.items.add(arr[i])
    }

    $('#plz_drag').css("display",'none')
    $('.file_list_header').css('display','flex')
    document.getElementById("files").files=dataTransfer.files;
})

결과


0개의 댓글