【问题标题】:How can I set preview of video file, selecting from input type='file'如何设置视频文件的预览,从 input type='file' 中选择
【发布时间】:2016-07-02 08:03:05
【问题描述】:

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

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

代码如下:

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

【问题讨论】:

    标签: javascript jquery html video html5-video


    【解决方案1】:

    @FabianQuiroga 是正确的,在这种情况下您应该更好地使用 createObjectURL 而不是 FileReader,但您的问题更多地与您设置 &lt;source&gt; 元素的 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:当您不再需要它时,不要忘记致电URL.revokeObjectURL($source[0].src)

    【讨论】:

    • 应该是公认的答案!顺便说一句,在任何时候不做 URL.revokeObjectURL($source[0].src) 有什么影响?
    • @CarlosArturoFyuler 在这种情况下(用户通过input[type=file] 提供文件,不是那么多......这里createObjectURL 返回的blobURI 只是包含指向用户磁盘上文件的直接符号链接, 所以内存影响不太重要。但在其他情况下,它确实会产生实际后果:来自生成或获取的 Blob 的未撤销 blobURI 会将其数据保存在内存中,直到会话结束。更糟糕的是,使用 MediaStream,如 gUM (在编写此答案时,cOU 仍然是显示 MediaStreams 的方式,现已弃用),它可能会阻止设备(例如网络摄像头)。
    • 感谢您的澄清 :)
    • $source.parent(...)[0].load 不是函数
    • @Kaiido 对不起,我对URL.revokeObjectURL($source[0].src) 了解不多,所以你能在上面的代码中告诉我我应该在哪里打电话给URL.revokeObjectURL($source[0].src)
    【解决方案2】:

    别忘了它使用了 jquery 库

    Javascript

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

    HTML

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

    【讨论】:

      【解决方案3】:

      如果您遇到此问题。那么您可以使用下面的方法来解决上述问题。

      这里是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>
      

      下面是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];
      }
      

      【讨论】:

        【解决方案4】:

        让一切变得简单

        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:

        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]);
            }
        }
        

        【讨论】:

          【解决方案5】:

          这是一个简单的解决方案

          document.getElementById("videoUpload").onchange = function(event) {
            let file = event.target.files[0];
            let blobURL = URL.createObjectURL(file);
            document.querySelector("video").style.display = 'block';
            document.querySelector("video").src = blobURL;
          }
          <input type='file'  id='videoUpload'/>
          
          <video width="320" height="240" style="display:none" controls autoplay>
            Your browser does not support the video tag.
          </video>

          解决方案是使用 vanilla js,所以你不需要 JQuery,它在 chrome 上测试和工作,Goodluck

          【讨论】:

            【解决方案6】:

            这是 VUE JS 上的示例: preview PICTURE

            Example SOURCE CODE - DRAG-DROP _part

            Example with RENDERing & createObjectURL() 使用 VIDEO.js

            附言我只是想改进“Pragya Sriharsh”解决方案:

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

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

            -> 所以:

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

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

            【讨论】:

            • jQuery 仍然被许多主要的 Web 平台使用,并且仅仅为了显示视频而编写整个 VUE 或 React 组件是不可行的。 jQuery 仍然相关且受支持。
            • 支持 Jquery,就像我的诺基亚 3310 仍然可以在我的网络上拨打电话一样。这并不意味着您不应该尝试与时俱进。 JQuery 是垃圾。
            猜你喜欢
            • 2021-05-24
            • 2011-04-01
            • 1970-01-01
            • 2010-11-20
            • 2010-12-08
            • 2018-05-11
            • 1970-01-01
            • 2019-11-16
            相关资源
            最近更新 更多