Javascript read file without using input

34,192

Solution 1

You simply can't do what you are trying to do. Setting the path for an input element through Javascript is not possible, as a security measure. Please check here: How to resolve the C:\fakepath?

Solution 2

You can launch chromium, chrome browser with --allow-file-access-from-files flag set, use fetch() of XMLHttpRequest() to request file from local filesystem.

fetch("file:///path/to/file")
.then(response => response.arrayBuffer())
.then(ab => {
  // do stuff with `ArrayBuffer` representation of file
})
.catch(err => console.log(err));

See also Read local XML with JS

Solution 3

The File API is not good to read local files without user intervention, but the Web API is (of course, within its limitations, like not working in Chromium without explicitly enabling access to local files and whatnot).

So, here it is, in case someone else needs a working example of how to load a local file without user intervention, i.e., without requiring user to push any INPUT button (but still giving the user a means to abort the loading).

Parameters: file name, request type (text, blob etc.), MIME type and a function to be executed after the file is completely loaded. File is loaded in variable X, which is then used to populated an object.

To abort the file reading, just click on the progress bar (also, just an example, not essential for the program to work). Because it is asynchronous, as many files as wanted may be read at the same time (one progress bar is created for each file).

I only created examples for a text file and a video, but it should work with any kind of files.

<html>
<head>
<meta charset="utf-8"/>
<script type="text/javascript">
function LoadFile(FileName,RespType,FileType,RunMe)
{   var AJAXFileReader=new XMLHttpRequest();

    // Creates new progress bar.
    var ProgressBar=CreateSVGProgBar("ProgressBars");

    AJAXFileReader.addEventListener("progress",
        function FRProgress(AJAXFREvt)
        {   // Calculate progress.
            var X=-1;

            if (AJAXFREvt.lengthComputable)
                X=Math.trunc(AJAXFREvt.loaded/AJAXFREvt.total*100);

            ShowProgressBar(ProgressBar,FileName,X);
        });

    AJAXFileReader.addEventListener("error",function FRFailed()
        {   // This will be executed if an error occurs.
            console.log("Error:",this.status);
        });

    AJAXFileReader.addEventListener("timeout",function FRTimeOut()
        {   // This will be executed if the reading times out.
            console.log("File reading timed out!");
        });

    AJAXFileReader.addEventListener("abort",
        function FRCancel()
        {   // This will confirm reading was aborted.
            console.log("File reading cancelled by user!");
        });

    ProgressBar.addEventListener("click",
        function KillMe()
        {   // Adds an abort command to the object.
            console.log(AJAXFileReader.readyState);
            if (AJAXFileReader.readyState!=4)
            {   console.log("Aborting file reading...");
                AJAXFileReader.abort();
            }
            ProgressBar.removeEventListener("click",KillMe);
        },
        false);

    AJAXFileReader.addEventListener("load",
        function Finished()
        {   // When reading is finished, send data to external function.
            if ((this.readyState==4)&&(this.status==200))
            {   ShowProgressBar(ProgressBar,FileName,100);
                RunMe(this.response);
                //ProgressBar.click();
            }
        },
        false);

    AJAXFileReader.open("GET",FileName,true);
    AJAXFileReader.overrideMimeType(FileType);
    AJAXFileReader.responseType=RespType;
    AJAXFileReader.timeout=10000; // Setting time-out to 10 s.

    AJAXFileReader.send();
}

function CreateSVGProgBar(AnchorId)
{   // Creates new SVG progress bar.
    var Parent=document.getElementById(AnchorId);
    var NewSVG=document.createElementNS("http://www.w3.org/2000/svg","svg");
    NewSVG.setAttribute("viewBox","0 0 102 22");
    NewSVG.setAttribute("width","102");
    NewSVG.setAttribute("height","22");
    Parent.appendChild(NewSVG);
    return NewSVG;
}

function ShowProgressBar(E,N,X)
{   // Show progress bar.
    var P=X<0?"???":X+"%";

    E.innerHTML="<text x=\"50\" y=\"16\" font-size=\"12\" fill=\"black\" stroke=\"black\" text-anchor=\"middle\">"+N+"</text><rect x=\"1\" y=\"1\" width=\""+X+"\" height=\"20\" fill=\""+(X<100?"#FF0000":"#0000FF")+"\" stroke=\"none\"/><rect x=\"1\" y=\"1\" width=\"100\" height=\"20\" fill=\"none\" stroke=\"black\" stroke-width=\"1\"/><text x=\""+X/2+"\" y=\"16\" font-size=\"12\" fill=\"black\" stroke=\"black\" text-anchor=\"middle\">"+P+"</text>";
}

function TracerOn(X)
{   // This will be executed after the file is completely loaded.
    document.getElementById("Tron").innerHTML=X;
}

function PlayIt(X)
{   // This will be executed after the file is completely loaded.
    var blob_uri=URL.createObjectURL(X);
    document.getElementById("MagicalBox").appendChild(document.createElement("source")).src=blob_uri;
}

function Startup()
{   // Run after the Page is loaded.
    LoadFile("example.txt","text","text/plain;charset=utf-8",TracerOn);
    LoadFile("video.mp4","blob","video/mp4",PlayIt);
}

</script>
</head>

<body onload="Startup()">

<div id="ProgressBars"></div>

<div id="Tron">Text...</div>

<video id="MagicalBox" width="400" controls>Video...</video>

</body>
</html>
Share:
34,192
user986959
Author by

user986959

Updated on October 19, 2020

Comments

  • user986959
    user986959 over 3 years

    I have this code and for a file to be converted into base64 I have to click on Choose file and then select it. I want to hardcode the file name so it is converted to base64 on page load.

    JavaScript:

    var handleFileSelect = function(evt) {
      var files = evt.target.files;
      var file = files[0];
    
      if (files && file) {
        var reader = new FileReader();
    
        reader.onload = function(readerEvt) {
          var binaryString = readerEvt.target.result;
          document.getElementById("base64textarea").value = btoa(binaryString);
        };
    
        reader.readAsBinaryString(file);
      }
    
      if (window.File && window.FileReader
          && window.FileList && window.Blob) {
        document.getElementById('filePicker')
            .addEventListener('change', handleFileSelect, false);
      } else {
        alert('The File APIs are not fully supported in this browser.');
      }
    };
    

    HTML:

    <div>
      <div>
        <label for="filePicker">Choose or drag a file:</label><br/>
        <input type="file" id="filePicker">
      </div>
      </br>
      <div>
        <h1>Base64 encoded version</h1>
        <textarea id="base64textarea"
            placeholder="Base64 will appear here"
            cols="50" rows="15">
        </textarea>
      </div>
    </div>
    

    EDIT: Thank you for your answers, they were really helpful.