如何设置视频文件的预览,从 input type='file' 中选择 [英] How can I set preview of video file, selecting from input type='file'

查看:19
本文介绍了如何设置视频文件的预览,从 input type='file' 中选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

代码如下:

$(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/*">

推荐答案

@FabianQuiroga 是对的,在这种情况下你应该更好地使用 createObjectURL 而不是 FileReader,但是你的问题更多是因为您设置了 元素的 src,因此您需要调用 videoElement.load().

@FabianQuiroga is right that you should better use createObjectURL than a FileReader in 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().

$(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:不要忘记调用 URL.revokeObjectURL($source[0].src) 当你不再需要它.

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

这篇关于如何设置视频文件的预览,从 input type='file' 中选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆