Search code examples
javascripthtmliframeinput-type-file

Using <input type="file"> to display uploaded files with iframe


I want to use a file input so that a user could upload a folder containing their site files, then the program finds the index file in the folder then displays it in the iframe.

I attepted to do this myself (shown below) using a folder containing a simple html and css file, but index.html would never load.

<!doctype html>
<html>
    <body>
        <input type="file" id="fileSelect" webkitdirectory>

        <iframe id="iframeView" height="400" width="600"></iframe>
        
        <script>
            //Instantiate to reduce visual complexity
            const frameElement = document.getElementById("iframeView");
            const fileElement = document.getElementById("fileSelect");
            
            //Call loadURL when a folder is selected
            fileElement.addEventListener("change", loadURL);
            
            //Get index.html file from folder and make it the iframe src
            function loadURL() {
                frameElement.src = fileElement.files["index.html"];
            }
        </script>
    </body>
</html>

Solution

  • Use Array#find to find the index.html file in the selected folder. And use The FileReader API to read its content.

    const frameElement = document.getElementById("iframeView");
    const fileElement = document.getElementById("fileSelect");
    fileElement.addEventListener("change", loadURL);
    
    function loadURL() {
      const files = Array.from(fileElement.files);
      const indexFile = files.find((file) => file.name === "index.html");
      if (indexFile) {
        const reader = new FileReader();
        reader.onload = function(e) {
          frameElement.src = e.target.result;
        };
        reader.readAsDataURL(indexFile);
      }
    }
    <input type="file" id="fileSelect" webkitdirectory />
    <iframe id="iframeView" height="400" width="600"></iframe>