0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【TypeScript】同じローカルファイルを読み込む

Last updated at Posted at 2020-11-30

はじめに

JavaScriptで同じローカルファイルを読み込もうとなったとき、JavaScriptで同じローカルファイルをもう一度読み込むに辿り着くかと思います。
ですが、TypeScriptで同じことをやろうとなった時、型に悩まされます。
本記事ではFileReaderを用いて、TypeScriptで同じローカルファイルを読み込む解決法の一つを提示していきます。
この記事のコードはstackblitzで試しました。

コード

HTML

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="./main.ts" async></script>
</head>
<body>
    <input type="file" id="input-file">
</body>
</html>

input type="file"を用いてファイルを取ってきます。

TypeScript

function main() {
    const reader = new FileReader();
    reader.addEventListener("load", e => {
        console.log(e.target.result);
    });

    const inputFile = document.getElementById("input-file");
    if (!inputFile) return;
    inputFile.addEventListener("change", e => {
        const target = e.target as HTMLInputElement;
        reader.readAsText(target.files[0]);
        target.value = "";
    });
}

main();

これでファイルを選択したあとconsoleにファイルの中身が表示されます。
HTMLInputElement型アサーションしてあげることで、e.targetのfileやvalueにアクセスできるようになります。

また、inputのvalueを空にしてやることで、同じファイルを読み込めるようになります。
こうなると、ファイル読み込みの横に表示されていた、現在選択されているファイルは何も選択されていない状態と同じになります。最後に読み込んだファイルを表示しておきたい場合は、上記のコードのtarget.valueinnerTextなどで表示してからtarget.value = "";すると良いかと思います。

おわりに

DOMに関連した型は知らないと解決が難しいです。
stackblitzは雑に便利なので使いましょう。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?