chaps
chaps

Reputation: 105

How do i open a file of any type in javascript and have it saved as a string

So, when you open any file in a text editor whether it be an image or a sound file or a peice of code, inside the text editor it comes up with the datatype in text format, how would i use javascript (in a html document) to open any file and save it into a variable as a string, like as presented in a text editor

//something like this

var file = getFile(c:/path/location/goes/here);
document.write(file);

//then it prints the files' text content onto the document

Upvotes: 1

Views: 521

Answers (1)

Nikhil Ghuse
Nikhil Ghuse

Reputation: 1288

You can use ajax to load you file or if you want pure js then try following code snippet

function readBlob() {

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

    var file = files[0];
    var start = 0;
    var stop = file.size - 1;

    var reader = new FileReader();

    // If we use onloadend, we need to check the readyState.
    reader.onloadend = function(evt) {
      if (evt.target.readyState == FileReader.DONE) { // DONE == 2
        document.getElementById('byte_content').textContent = evt.target.result;
        document.getElementById('byte_range').textContent = 
            ['Read bytes: ', start + 1, ' - ', stop + 1,
             ' of ', file.size, ' byte file'].join('');
      }
    };

    var blob = file.slice(start, stop + 1);
    reader.readAsBinaryString(blob);
  }
<style>
  #byte_content {
    margin: 5px 0;
    max-height: 100px;
    overflow-y: auto;
    overflow-x: hidden;
  }
  #byte_range { margin-top: 5px; }
</style>

<input type="file" id="files" name="file" onchange ="readBlob()" />
<div id="byte_range"></div>
<div id="byte_content"></div>

Upvotes: 3

Related Questions