user1580096 user1580096 - 3 months ago 76
Javascript Question

FakePath issue in Chrome browser

I am making a browser based audio player. So for making a playlist from the local directory I am using :

<input type="file" id="getFile" />


Then I am using a button to confirm the playlist.On clicking the button I am calling a javascript function to change the src of the audio tag to play the new audio file selected in the playlist. I want the exact path of the file from the input file to run in the HTML5 audio player but it starts taking the path as C://Fakepath/filename.mp3. Can someone help me with this.

Answer

This is a security feature, by design. You should not be able to read the original file path of a file input into a browser form. File input is for reading file contents only, not metadata like path on the user's file system.

The good news is that you don't need the original file path. You can use FileReader's readAsDataURL to convert the file contents into a base64-encoded data URL and use that as the audio src. To read from #myUploadInput and output through #myAudioElement (also available as a working fiddle):

var reader = new FileReader();

reader.onload = function (event) {
    document.getElementById("myAudioElement").src = event.target.result;
};

reader.readAsDataURL(document.getElementById("myUploadInput").files[0]);