Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

javascript - File data from input element

In Firefox 3 it is possible to access the contents of a <input type="file"> element as in the following.

Assume a form with the following element:

<input type="file" id="myinput">

Now the data of the file selected can be accessed with:

// Get the file's data as a data: URL
document.getElementById('myinput').files[0].getAsDataURL()

Is there a cross-browser way to accomplish the same thing?

Firefox documentation for this feature:

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is possible in at least Chrome, Firefox and Safari: Reading Files. see associated jsfiddle

function readBlob(opt_startByte, opt_stopByte) {

    var files = document.getElementById('files').files;
    if (!files.length) {
      alert('Please select a file!');
      return;
    }
    var file = files[0];
    var start = parseInt(opt_startByte) || 0;
    var stop = parseInt(opt_stopByte) || 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 = _.reduce(evt.target.result, 
              function(sum, byte) {
                  return sum + ' 0x' + String(byte).charCodeAt(0).toString(16);
              }, '');
        document.getElementById('byte_range').textContent = 
            ['Read bytes: ', start + 1, ' - ', stop + 1,
             ' of ', file.size, ' byte file'].join('');
      }
    };

    var blob;
    if (file.slice) {
        blob = file.slice(start, stop + 1);
    }else if (file.webkitSlice) {
      blob = file.webkitSlice(start, stop + 1);
    } else if (file.mozSlice) {
      blob = file.mozSlice(start, stop + 1);
    }
    console.log('reader: ', reader);
    reader.readAsBinaryString(blob);
  }

  document.querySelector('.readBytesButtons').addEventListener('click', function(evt) {
    if (evt.target.tagName.toLowerCase() == 'button') {
      var startByte = evt.target.getAttribute('data-startbyte');
      var endByte = evt.target.getAttribute('data-endbyte');
      readBlob(startByte, endByte);
    }
  }, false);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...