Javascript 如何设置视频文件的预览,从 input type='file' 中选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36035721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:32:53  来源:igfitidea点击:

How can I set preview of video file, selecting from input type='file'

javascriptjqueryhtmlvideohtml5-video

提问by Ronak Patel

In one of my module, I need to browse video from input[type='file'], after that I need to show selected video before starting upload.

在我的一个模块中,我需要从 input[type='file'] 浏览视频,之后我需要在开始上传之前显示选定的视频。

I am using basic HTML tag to show. but it is not working.

我正在使用基本的 HTML 标签来显示。但它不起作用。

Here is code:

这是代码:

$(document).on("change",".file_multi_video",function(evt){
  
  var this_ = $(this).parent();
  var dataid = $(this).attr('data-id');
  var files = !!this.files ? this.files : [];
  if (!files.length || !window.FileReader) return; 
  
  if (/^video/.test( files[0].type)){ // only video file
    var reader = new FileReader(); // instance of the FileReader
    reader.readAsDataURL(files[0]); // read the local file
    reader.onloadend = function(){ // set video data as background of div
          
          var video = document.getElementById('video_here');
          video.src = this.result;
      }
   }
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<video width="400" controls >
              <source src="mov_bbb.mp4" id="video_here">
            Your browser does not support HTML5 video.
          </video>


 <input type="file" name="file[]" class="file_multi_video" accept="video/*">

回答by Kaiido

@FabianQuiroga is right that you should better use createObjectURLthan a FileReaderin this case, but your problem has more to do with the fact that you set the src of a <source>element, so you need to call videoElement.load().

@FabianQuiroga 是正确的,在这种情况下您应该createObjectURL比 a更好地使用FileReader,但是您的问题更多地与您设置<source>元素的 src 的事实有关,因此您需要调用videoElement.load().

$(document).on("change", ".file_multi_video", function(evt) {
  var $source = $('#video_here');
  $source[0].src = URL.createObjectURL(this.files[0]);
  $source.parent()[0].load();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<video width="400" controls>
  <source src="mov_bbb.mp4" id="video_here">
    Your browser does not support HTML5 video.
</video>

<input type="file" name="file[]" class="file_multi_video" accept="video/*">

Ps: don't forget to call URL.revokeObjectURL($source[0].src)when you don't need it anymore.

ps:不用的时候别忘了打电话URL.revokeObjectURL($source[0].src)

回答by Fabian Quiroga

Do not forget that it uses jquery library

不要忘记它使用jquery库

Javascript

Javascript

$ ("#video_p").change(function () {
   var fileInput = document.getElementById('video_p');
   var fileUrl = window.URL.createObjectURL(fileInput.files[0]);
   $(".video").attr("src", fileUrl);
});

Html

html

< video controls class="video" >
< /video >

回答by Pragya Sriharsh

If you are facing this issue. Then you can use the below method to resolve the above issue.

如果你正面临这个问题。然后您可以使用以下方法来解决上述问题。

Here is the html code:

这是html代码:

//input tag to upload file
<input class="upload-video-file" type='file' name="file"/>

//div for video's preview
 <div style="display: none;" class='video-prev' class="pull-right">
       <video height="200" width="300" class="video-preview" controls="controls"/>
 </div>

Here is the JS function below:

下面是JS函数:

$(function() {
    $('.upload-video-file').on('change', function(){
      if (isVideo($(this).val())){
        $('.video-preview').attr('src', URL.createObjectURL(this.files[0]));
        $('.video-prev').show();
      }
      else
      {
        $('.upload-video-file').val('');
        $('.video-prev').hide();
        alert("Only video files are allowed to upload.")
      }
    });
});

// If user tries to upload videos other than these extension , it will throw error.
function isVideo(filename) {
    var ext = getExtension(filename);
    switch (ext.toLowerCase()) {
    case 'm4v':
    case 'avi':
    case 'mp4':
    case 'mov':
    case 'mpg':
    case 'mpeg':
        // etc
        return true;
    }
    return false;
}

function getExtension(filename) {
    var parts = filename.split('.');
    return parts[parts.length - 1];
}

回答by kostia7alania

This is example on VUE JS: preview PICTURE

这是 VUE JS 上的示例: 预览图片

Example SOURCE CODE - DRAG-DROP _part

示例源代码 - DRAG-DROP _part

Example with RENDERing & createObjectURL() using VIDEO.js

使用 VIDEO.js 的 RENDERing 和 createObjectURL()示例

p.s. i just want to improve "Pragya Sriharsh" solution:

ps我只想改进“ Pragya Sriharsh”解决方案:

const = isVideo = filename =>'m4v,avi,mpg,mov,mpg,mpeg'
.split(',')
.includes( getExtension(filename).toLowerCase() )

And .. please don't use JQuery, it's now 2k19:-);

而且..请不要使用JQuery,现在是2k19:-);

-> So:

-> 所以:

const getExtension = filename => {
    const parts = filename.split('.');
    return parts[parts.length - 1];
}

... And let the rest of the work will be done by Webpack 4!

... 剩下的工作将由 Webpack 4 来完成!

回答by Usama Shahid

Lets make it easy

让我们轻松一点

HTML:

HTML:

<video width="100%" controls class="myvideo" style="height:100%">
<source src="mov_bbb.mp4" id="video_here">
Your browser does not support HTML5 video.
</video>



JS:

JS:

function readVideo(input) {

if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function(e) {

        $('.myvideo').attr('src', e.target.result);
    };

    reader.readAsDataURL(input.files[0]);
}
}