how to Preview the video file that user wants to upload on the website (PHP, FiileAPI JS)

橙三吉。 提交于 2019-12-06 01:13:49

You can either use FileReader or createObjectURL. They'll both get the job done, but FileReader has slightly broader support in browsers.

createObjectURL will run synchronously and return a Blob URL, a short string referencing the file in memory. and you can free it up immediately after you're done using it.

FileReader will run asynchronously, requiring a callback, providing a Data URI, a much longer string representing the whole file. This can be very big and will be freed from memory in Javascript garbage collection.

Here's an example that first tries createObjectURL and falls back to FileReader. (Please provide your own error checking, etc.)

var video = document.getElementById('video'),
    input = document.getElementById('input');

input.addEventListener('change', function (evt) {
    var reader = new window.FileReader(),
        file = evt.target.files[0],
        url;

        reader = window.URL || window.webKitURL;

    if (reader && reader.createObjectURL) {
        url = reader.createObjectURL(file);
        video.src = url;
        reader.revokeObjectURL(url);  //free up memory
        return;
    }

    if (!window.FileReader) {
        console.log('Sorry, not so much');
        return;
    }

    reader = new window.FileReader();
    reader.onload = function(evt) {
       video.src = evt.target.result;
    };
    reader.readAsDataURL(file);
}, false);

Working example here: http://jsbin.com/isodes/1/edit

Mozilla has a more detailed article with instructions on how to upload once you've got your file.

IE10 supports both, but IE9 supports neither, so you'll have to fall back to a regular form upload without a preview.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!