views:

131

answers:

2

How can i upload a file and get its contents in javascript. For example, i want to upload an mp3 and play it in the html5 audio tag without having it on the server. Is this possible?

+2  A: 

When uploading files, javascript cannot (without plug-in support) gain access to the file. To do what you are asking for, you must actually upload the file to the server and then have your javascript be a client to your server to retrieve the file, and then play it.

Jaxidian
+1  A: 

You can read local files from JavaScript with the File API. Only Firefox >= 3.6 implements it I think and it's still a Working Draft.

Demo (if you try it in Firefox, it only supports .wav and .ogg audio files):

<input id="input" type="file">
<button onclick="play()">play</button>
<script>
  function play() {
    var file = document.getElementById("input").files[0];
    var reader = new FileReader();
    reader.onload = function(e) {
      var audio = new Audio(e.target.result);
      audio.play();
    }
    reader.readAsDataURL(file);
  }
</script>

See also developer.mozilla.org/en/Using_files_from_web_applications

Sylvain
Thanks! Got it working
NebNeb