자바스크립트 폴더 경로 반환하기

type이 file로 설정된 input 엘리먼트로는 파일만 고를 수 있다. 스탠더드 애트리뷰트는 아니지만 크로뮴 베이스드 웹 브라우저들에서는 제대로 작동하는 webkitdirectory를 이용하면 폴더를 선택할 수 있다.

​그런데 이렇게 해도 버튼의 캡션은 여전히 파일 선택으로 되어 있다. 아래 예제에서는 input를 보이지 않게 하고 select folder라는 캡션의 button을 만든 뒤 버튼의 onclick 이벤트에 input이 작동하도록 했다.

<!DOCTYPE html>

<button onclick="document.getElementById('chooseFolder').click()">Select Folder</button>
<input id="chooseFolder" style="display: none" type='file' webkitdirectory>

<button onclick="showPath()">Show Path</button>

<script>
    function showPath()
    {
        let _fullPath = document.getElementById('chooseFolder').files[0].webkitRelativePath;
        let _path = _fullPath.substring(0, _fullPath.lastIndexOf('/'));

        console.log(_path);
    }
</script>

webkitdirectory를 통해 반환되는 건 모든 파일들의 객체일 뿐 폴더의 그것은 아니다.

If the user chooses PhotoAlbums, then the list reported by files will contain File objects for every file listed above—but not the directories.
HTMLInputElement: webkitdirectory property

따라서 폴더의 이름을 구하려면 해당 폴더에 있는 파일의 이름을 파싱해야 한다. 이렇게 폴더 이름 파싱이 모든 파일들에 접근을 한 뒤 이뤄지므로 폴더 안에 파일들이 많으면 시간이 오래 걸린다.