LoginSignup
1
0

More than 3 years have passed since last update.

ファイルを DATA URI に変換するフォーム

Last updated at Posted at 2020-03-27

ファイルを DATA URI に変換するフォーム

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

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>DATA URI 変換</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
  <input type="file" id="fileform">
  <br>
  <br>
  <textarea id="datauri" cols="100" rows="30"></textarea>
  <br>
  <button type="button" id="copybutton">コピー</button>
  <script>
    const toBase64DataUri = file => new Promise(resolve => {
      const reader = new FileReader();
      reader.onload = () => resolve(reader.result);
      reader.readAsDataURL(file);
    });

    document.getElementById("fileform").addEventListener("input", async (e) => {
      const file = e.target.files[0];
      const datauri = await toBase64DataUri(file);
      document.getElementById("datauri").value = datauri;
    }, false);

    document.getElementById("copybutton").addEventListener("click", () => {
      document.getElementById("datauri").select();
      document.execCommand("copy");
    }, false);
  </script>
</body>

</html>

ファイルを DATA URI に変換してる部分

const toBase64DataUri = file => new Promise(resolve => {
  const reader = new FileReader();
  reader.onload = () => resolve(reader.result);
  reader.readAsDataURL(file);
});

ファイルを DATA URI に変換してる部分を呼び出している部分

const datauri = await toBase64DataUri(file);
1
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
1
0