using the result of a file selected by the user inside a script

I am trying to use the name of a file selected by a user inside a script. If I have a input form element as:

<input id="browse" type="file" name="image_field"/>

and my script as:

function getVideoDimensionsOf(url){
return new Promise(function(resolve){
    // create the video element
    video = document.createElement('video');

    // place a listener on it
    video.addEventListener( "loadedmetadata", function () {
        // retrieve dimensions
        height = this.videoHeight;
        width = this.videoWidth;
        // send back result
        resolve({
            height : height,
            width : width
        });
    }, false );

    // start download meta-datas
    video.src = url;
});
}

getVideoDimensionsOf("http://clips.vorwaerts-gmbh.de/VfE_html5.mp4")
.then(function(dimensions){
console.log("Video width: " + dimensions.width) ;
console.log("Video height: " + dimensions.height) ;
alert("Video width: " + dimensions.width + " Video height: " + dimensions.height);
});

What do I have to do to use the content of id="browse" to replace "http://clips.vorwaerts-gmbh.de/VfE_html5.mp4"

Many thanks in advance for your time.

728x90

2 Answers using the result of a file selected by the user inside a script

You can use an object URL for this via createObjectURL:

video.src = URL.createObjectURL(document.getElementById("browse").files[0]);

It's best to revoke it when you're done with it (perhaps in your loadedmetadata callback):

URL.revokeObjectURL(video.src);

1 months ago

Check this:

function getVideoDimensionsOf(url){
return new Promise(function(resolve){
    // create the video element
    video = document.createElement('video');

    // place a listener on it
    video.addEventListener( "loadedmetadata", function () {
        // retrieve dimensions
        height = this.videoHeight;
        width = this.videoWidth;
        // send back result
        resolve({
            height : height,
            width : width
        });
    }, false );

    // start download meta-datas
    video.src = url;
});
}

const inputElement = document.getElementById("browse");
inputElement.addEventListener("change", handleFiles, false);

function handleFiles() {
  const fileList = this.files;
  console.log(this.files[0].name);

  getVideoDimensionsOf(URL.createObjectURL(this.files[0]))
.then(function(dimensions){
console.log("Video width: " + dimensions.width) ;
console.log("Video height: " + dimensions.height) ;
alert("Video width: " + dimensions.width + " Video height: " + dimensions.height);
});
}

https://jsfiddle.net/ch14trm0/1/

1 months ago