NebNeb
NebNeb

Reputation: 339

Javascript Upload to self

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?

Upvotes: 2

Views: 547

Answers (2)

Sylvain
Sylvain

Reputation: 86

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

Upvotes: 1

Jaxidian
Jaxidian

Reputation: 13511

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.

Upvotes: 1

Related Questions