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?
Asked
Active
Viewed 527 times
2
-
Your question is confusing: You want to "upload a file" and then play it "without having it on the server"? First you want it on the server, then you don't..? – kwah Dec 17 '12 at 19:25
-
For those who are looking at this page now for an answer to the question, if you are specifically looking for how to upload an mp3 and play it in an html5 audio tag, check out this working answer: https://stackoverflow.com/a/47584467/6901876 – Cannicide Oct 31 '19 at 21:56
2 Answers
1
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
- 13,081
- 8
- 83
- 125
1
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
- 86
- 1
- 3