Load text files via drag and drop in Javascript 

This article can be read in about 5 minutes.
PR

The purpose 

This uses JavaScript to read a locally saved text file via drag and drop.

For reading files using a file selector, see the following page.

PR

Load with the Filesystem API.

You can upload a file by dragging and dropping it into the 500×500 area displayed in the HTML below.

<!doctype html>
<html lang="ja">
<head>
    <meta charset="utf-8" />
    <title>text読込</title>
</head>
<body>
    <div id="droparea" style="border:solid;width:500px;height:500px"></div>
    <script>
        document.getElementById("droparea").addEventListener("dragover", () => {
            event.preventDefault();
        });
        document.getElementById("droparea").addEventListener("drop", loadText);

        async function loadText(event) {
            event.preventDefault();
            const items = event.dataTransfer.items;
            if (items[0].kind == "file") {
                const handle = await items[0].getAsFileSystemHandle();
                const file = await handle.getFile();
                if (file.type != "text/plain") return;
                const text = await file.text();
                console.log(text);
            }
        };
    </script>

</body>
</html>

The following code defines the actions for during dragging and when dragging is dropped.

dragover is the event that fires while dragging, and drop is the event that fires when the dragged item is dropped.

You need to call event.preventDefault(); within the dragover and drop events. Otherwise, a page reload will occur when dropping files. (I’m calling it within loadText for the drop event.)

        document.getElementById("droparea").addEventListener("dragover", () => {
            event.preventDefault();
        });
        document.getElementById("droparea").addEventListener("drop", loadText);

The following code is executed on drop.

It checks if the dropped item is a file using (items[0].kind == "file") and then verifies that it’s not a plain text file using (file.type != "text/plain"). If both conditions are true, the file’s content is read as text using const text = await file.text();. The text variable then stores the file’s content as a String.

        async function loadText(event) {
            event.preventDefault();
            const items = event.dataTransfer.items;
            if (items[0].kind == "file") {
                const handle = await items[0].getAsFileSystemHandle();
                const file = await handle.getFile();
                if (file.type != "text/plain") return;
                const text = await file.text();
                console.log(text);
            }
        };
PR

Result

 We are able to load a locally saved text file using drag and drop. 

comment

Copied title and URL