I tried using base64 to get image data:
function previewFile() {
const preview = document.getElementById('video1');
const file = document.querySelector('input[type=file]').files[0];
const reader = new FileReader();
reader.addEventListener("load", function() {
// convert to base64
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
<input type="file" onchange="previewFile()"><br>
<video width="320" height="240" id="video1" controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
This script makes you upload an mp4 file and then it will display it.
The problem is that base64 is too way long. Is there any other way to get the file data but shorter?
CodePudding user response:
You want to use Blob
url for shorter src.
Convert Base64 to Blob Change:
reader.result
to:
window.URL.createObjectURL(file)
function previewFile() {
const preview = document.getElementById('video1');
const file = document.querySelector('input[type=file]').files[0];
const reader = new FileReader();
reader.addEventListener("load", function() {
// convert to base64
preview.src = window.URL.createObjectURL(file);
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
<input type="file" onchange="previewFile()"><br>
<video width="320" height="240" id="video1" controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>