Search code examples
javascriptreactjshtml5-videowidthmedia

Get dimensions of mp4 on user upload reactjs


I'm creating a webpage that has a user upload a file. When they upload the file I need to be able to get the width and height of what they uploaded. The site only accepts media. I got the width and height of images working as you can just grab it from the metadata when it is loaded, but I am unable to get this for videos.

    var video = document.createElement('video');

    video.onloadedmetadata = () => {
        console.log("Video loaded!");
        alert("width: " + this.width + "\n" + "height: " + this.height);
    };
    video.onerror = () => {
        alert ("Error!");
    };
    video.src = _URL.createObjectURL(files[0]);

This is what I currently have but always get the width and height to be 0. I have seen some solutions to this using Jquery but none with react.

Any ideas as to how this can be done? Thank you


Solution

  • If I understand your question correctly, then you'd be wanting to access the videoWidth and videoHeight properties on the video element.

    So for instance, try updating your onloadedmetadata handler like so:

    video.onloadedmetadata = () => {
        console.log("Video loaded!");
        alert("width: " + video.videoWidth + "\n" + "height: " + video.videoHeight);
    };
    

    Hope that helps!