javascript イベント発生元のfileの名前を取得する

javascript イベント発生元のfileの名前を取得する

javascriptで、イベント発生元のfileの名前を取得するサンプルコードを掲載してます。ブラウザはchromeを使用しています。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 106.0.5249.103

イベント発生元のfileの名前を取得

イベント発生元の「file」の名前を取得するには、「Event.target.files[i].name」を使用します。

<input type="file" id="f">

<script>

'use strict';

function hoge(e){
  console.log(e.target.files[0].name)
}

document.getElementById("f").addEventListener('change', hoge, false)

</script>

実行結果を確認すると、選択されたファイルの名前が取得されていることが確認できます。

また、以下のコードを、

function hoge(e){
  console.log(e.target.files[0].name)
}

document.getElementById("f").addEventListener('change', hoge, false)

アロー関数とdocument.getElementByIdを省略して、簡潔に記述することもできます。

const hoge = (e) =>{
  console.log(e.target.files[0].name)
}

f.addEventListener('change', hoge, false)

サンプルコード

以下は、
「実行」ボタンをクリックした際に、クリック元のfileの名前を表示するサンプルコードとなります。

※cssには「tailwind」を使用して、アロー関数で関数は定義してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
</head>

<script>

  window.onload = () => {
    
    f.addEventListener('change', (e) => bar.innerHTML = e.target.files[0].name, false)

  }

</script>

<body>
  <div class="container mx-auto my-56 w-1/3 px-4">

    <div id="sample" class="flex flex-col justify-center">
      
      <h1 id="bar" class="font-semibold text-gray-500 text-lg mr-auto"></h1>

      <label
        class="w-64 flex flex-col items-center px-4 py-6 bg-white rounded-md shadow-md tracking-wide uppercase border border-blue cursor-pointer hover:bg-purple-600 hover:text-white text-purple-600 ease-linear transition-all duration-150">        
        <span class="mt-2 text-base leading-normal">Select a file</span>
        <input id="f" type='file' class="hidden" />
      </label>

    </div>

  </div>
</body>

</html>

実行結果を確認すると、名前が表示されていることが確認できます。