Ashwin Hegde
Ashwin Hegde

Reputation: 1771

HTML5 File API with filename path

I have following code to read file through HTML5 File API. I have uploaded the file via input=file element. Following is the code block.

<input type="file" id="files" name="file" />
<button id="readFile">Read File</button>
<output id="content"></output>

<script>

function readFile() 
{
    /* Get the reference of the inpout element. */
    var files = document.getElementById('files').files;
    console.log(files);

    if (!files.length) 
    {
      alert('Please select a file!');
      return;
    }

    /* Reading the first file selected. You can process other files similarly in loop. */
    var file = files[0];

    /* Instantiate the File Reader object. */
    var reader = new FileReader();

    /* onLoad event is fired when the load completes. */
    reader.onload = function(event) {
        document.getElementById('content').textContent = event.target.result;      
    };

    /* The readAsText method will read the file's data as a text string. By default the string is decoded as 'UTF-8'. */
    reader.readAsText(file);
}

document.getElementById('readFile').addEventListener('click', function(event) {
     readFile();
  }, false);

</script>

What if I don't want to uploaded the file and provide filepath via input=type element to HTML5: File API to read the file and display it?

I know that the HTML5: File API don't take direct file path. Is there any solution ?

Upvotes: 24

Views: 36275

Answers (2)

chaity
chaity

Reputation: 155

Latest version of IE return the complete absolute path of your file in the textbox. You may want to use: var filePath = document.getElementById("myFile").value; to get the absolute path

P.S. tried only on IE 11

Upvotes: 0

Majid Kalkatechi
Majid Kalkatechi

Reputation: 691

For Security reason, the browsers does not allow access to absolute path & file systems directly to Javascript. You can only get the file name by calling the 'val()' function in javascript and nothing more.

So don't waste your time.

Upvotes: 27

Related Questions