Reputation: 3263
I need a way to let users select a local video file as source for my html video element.
Setting the source doesn't seem to work because I can't access the full path from a standard javascript file dialog.
I tried the following:
//THE VIDEO ELEMENT
<video id="video1" muted>
<source src="" type="video/mp4" />
</video>
//THE DIALOG BUTTON TO SET VIDEO SOURCE
<input type='file' onchange="readURL(this);" />
<script>
var video = document.getElementById("video1");
function readURL(input) {
//THE METHOD THAT SHOULD SET THE VIDEO SOURCE
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
video.src = input.files[0]
};
}
}
</script>
How can I create a button that allows to select and upload local video files into the HTML5 video element?
Upvotes: 2
Views: 4196
Reputation: 1
For myself I solved it in separated js and html files like this:
html:<input id="file" type='file'/>
javascript:
document.getElementById('file').onchange = function(){
console.log('test');
readURL(this);
}
function readURL(input) {
//THE METHOD THAT SHOULD SET THE VIDEO SOURCE
if (input.files && input.files[0]) {
var file = input.files[0];
var url = URL.createObjectURL(file);
console.log(url);
var video = document.getElementById("video1");
var reader = new FileReader();
reader.onload = function() {
video.src = url;
video.play();
}
reader.readAsDataURL(file);
}
}
Upvotes: 0
Reputation: 798
I made some changes and work's fine! I tested in Chrome and Firefox.
//THE VIDEO ELEMENT
<video id="video1" muted>
<source src="" type="video/mp4" />
</video>
//THE DIALOG BUTTON TO SET VIDEO SOURCE
<input id="file" type='file' onchange="readURL(this);" />
<script>
var video = document.getElementById("video1");
function readURL(input) {
//THE METHOD THAT SHOULD SET THE VIDEO SOURCE
if (input.files && input.files[0]) {
var file = input.files[0];
var url = URL.createObjectURL(file);
console.log(url);
var reader = new FileReader();
reader.onload = function() {
video.src = url;
video.play();
}
reader.readAsDataURL(file);
}
}
</script>
Upvotes: 2