0

I want to open a file in Javascript that the user selects from the local filesystem. I can get the file name but I don't know how to open it.

<form action='' method='POST' enctype='multipart/form-data'>
    <input id="archiveFile" type='file' name='userFile'><br>
    <script>
        archiveFile.onchange = function (e)
        {
            console.log(archiveFile.value);
            // open the file here
        }
    </script>
</form>

2 Answers 2

1

You need for the HTML5 FileReader Api, further information are there: https://developer.mozilla.org/en-US/docs/Web/API/FileReader

here is a polyfill using Flash: https://github.com/Jahdrien/FileReader

This is a very well-made article: http://www.html5rocks.com/en/tutorials/file/dndfiles/#toc-reading-files it explains almost everything.

working example:

function FileReaderCtrl() {
  var self = this;
  var field = document.getElementById('fieldFile');
  var result = document.getElementById('result');
  
  self.readFile = function(event) {
    var res = event.target.result;
    var image = '<img src="'+ (res || '') +'"/>';
    result.innerHTML = image;
    console.log(image);
  };
  
  field.onchange = function(event) {
    var files = field.files;
    var reader;
    if(files.length < 1) {
      return;     
    }
    
    reader = new FileReader();
    reader.onload = self.readFile;
    reader.readAsDataURL(files[0]);
    
  }
}

document.addEventListener('DOMContentLoaded', FileReaderCtrl);
#result {
  width: 200px;
  height: 200px;
  
  background: lightcoral;
  margin: 1em auto;
}
img {max-width: 100% }
<label for="fieldFile">Select an Image:<br><input type="file" id="fieldFile"/></label>
<div id="result"></div>

Sign up to request clarification or add additional context in comments.

Comments

1

Substitute archiveFile.files for archiveFile.value. The value of an input type="file" element is not a FileList or File object

For historical reasons, the value IDL attribute prefixes the file name with the string "C:\fakepath\"

archive.files would be the FileList object, from which you can iterate the selected File object or objects if multiple attribute is set at input type="file" element. For example, archiveFile.files[0] to view properties of individual File object

<form action='' method='POST' enctype='multipart/form-data'>
  <input id="archiveFile" type='file' name='userFile'>
  <br>
  <script>
    archiveFile.onchange = function(e) {
      console.log(archiveFile.files, archiveFile.files[0]);
      // open the file here
    }
  </script>
</form>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.