Things I want to do
This JavaScript code loads a locally stored text file via drag-and-drop.
For instructions on loading using a file selector, please refer to the following page.
Reading via File System API
You can load files by dragging and dropping them into the 500×500 area displayed in the following HTML.
<!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 operations performed while dragging and during dragging.
`dragover` is the event that occurs while dragging, and `drop` is the event that occurs when dropping.
You need to call `event.preventDefault();` within the `dragover` and `drop` events. If you don’t, a page transition will occur when a file is dropped. (It’s called within `loadText` during the `drop` event.)
document.getElementById("droparea").addEventListener("dragover", () => {
event.preventDefault();
});
document.getElementById("droparea").addEventListener("drop", loadText);The following code is called when a drop occurs.
(items[0]The code checks that the dropped item is a file using `.kind == ‘file’)` and that it is a Text file using `(file.type != ‘text/plain’)`. Then, it reads the contents of the file as a text file using `const text = await file.text();`. The contents of the file are saved to the `text` variable in String format.
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);
}
};Result
I was able to load a locally saved text file using drag and drop.


コメント