Load uploaded video into html

30 Views Asked by At

I want the user to be able to upload a video and then, by clicking a button, load the video into a tag to view.

Here is an example:

HTML:

function loadvideo() {         video = document.getElementById('videoinput').files[0];         videoelement = document.getElementById('videopreview');         videoelement.src = video; ///I don't think this will work as we need to read the file first??     }
<html>         <body>             <input type="file" accept="mp4" id="videoinput">             <video id="videopreview">             <button onclick="loadvideo()">Load The Video</button>             <script type="javascript src="myscript.js">         </body>     </html>

2

There are 2 best solutions below

1
Rayzel On

document.getElementById('videoinput').addEventListener('change',
(e) => {
    let fileInput = e.target.files[0];
    let videoElement = document.getElementById('videopreview');
    let reader = new FileReader();
    reader.onload = function(e2) {
        videoElement.src = e2.target.result;
        videoElement.style.display = 'block';
    };
    reader.readAsDataURL(fileInput);
});
<input type="file" accept="video/mp4" id="videoinput">
<video id="videopreview" controls style="display:none;"></video>

0
Roko C. Buljan On

Preview video before upload

If you want to preview a video file before actually uploading it, you could send the Input's Event.target.files[0] into URL.createObjectURL to a newly created <video> element's src attribute.
To then insert such VideoElement into a designated preview wrapper, you can use Element.replaceChildren()

// DOM utils:

const el = (sel, par = document) => par.querySelector(sel);
const elNew = (tag, prop) => Object.assign(document.createElement(tag), prop);


// Preview video before upload:

const elInput = el(`[name="video"]`);
const elPreview = el("#preview");

elInput.addEventListener("change", (evt) => {
  elPreview.replaceChildren(elNew("video", {
    src: URL.createObjectURL(evt.target.files[0]),
    controls: true,
    height: 150
  }));
});
<input name="video" type="file" accept="video/*">
<div id="preview"></div>