Beispiel:Create-object-url.html

Aus SELFHTML-Wiki
Wechseln zu: Navigation, Suche
<!DOCTYPE html>
<html lang="de">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0;" />
  <link rel="stylesheet" media="screen" href="./Beispiel:SELFHTML-Beispiel-Grundlayout.css" />
  <title>Beispiel: createObjectURL</title>
  <style>
    body { font-family: Arial, sans-serif; }
      
    label {
      display: block;
      margin-top: 0.5em;
      width: fit-content;
    }

    textarea {
      width: 90vw;
      height: 4em;
    }

  </style>
  <script>
    // Funktion zum Generieren der URL
    function generateURL() {
      // Input-Felder auslesen
      var inputText = document.getElementById("input_text").value;
      var inputType = document.getElementById("input_type").value;
      var inputName = document.getElementById("input_name").value;
      var link = document.getElementById("download");

      // Falls Link bereits vorhanden, Speicherleck vermeiden
      if (link.href) {
        URL.revokeObjectURL(link.href);
      }

      // Binary Large OBject (BLOB) erstellen
      var blob = new Blob([inputText], {
        type: inputType
      });

      // Alles auf den Link schmeißen
      link.href = URL.createObjectURL(blob);
      link.download = inputName;
      link.textContent = "'" + inputName + "' herunterladen";
      link.hidden = false;
    }
      
    // Wenn das Dokument geladen ist...
    window.addEventListener("DOMContentLoaded", function() {
      // ... füge Event-Listener hinzu!
      document.getElementById("url_form").addEventListener("submit", function(submitEvent){
        submitEvent.preventDefault();
        generateURL();
      });
    });
  </script>
</head>
<body>
  <h1>Beispiel: JavaScript URL.createObjectURL</h1>
  <main>
    <form id="url_form">
      <label for="input_text">Inhalt: </label>
      <textarea id="input_text" width="80" height="25">Hallo Welt!</textarea>
      <label for="input_type">MIME-Typ: </label>
      <input type="text" id="input_type" list="mime" />
      <label for="input_name">Vorgeschlagener Dateiname: </label>
      <input type="text" id="input_name" value="test.txt" />
      <datalist id="mime">
        <option value="text/css" />
        <option value="text/html" />
        <option value="image/svg+xml" />
        <option value="text/plain" />
      </datalist>
      <br/>
      <button id="generate">Download-URL generieren</button>
      <a hidden download="" id="download">Noch nichts</a>
    </form>
  </main>
</body>
</html>