1

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>

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?

1
  • 1
    Use blob url for shorter data Commented Nov 20, 2021 at 13:04

1 Answer 1

0

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.