Как настроить предварительный просмотр видеофайла, выбрав input type='file'
В одном из моих модулей мне нужно просмотреть видео с ввода [ 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/*">
Ответы
Ответ 1
@FabianQuiroga прав, что вам лучше использовать createObjectURL
, чем a FileReader
в этом случае, но ваша проблема больше связана с тем, что вы устанавливаете src элемента <source>
, поэтому вам нужно вызовите 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/*">
Ответ 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
$(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/*">
Ответ 4
Если вы столкнулись с этой проблемой. Затем вы можете использовать приведенный ниже метод для решения вышеуказанной проблемы.
Вот HTML-код:
//input tag to upload file
<input class="upload-video-file" type='file' name="file"/>
//div for video 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];
}
Ответ 5
Это пример на VUE JS: предварительный просмотр изображения
Пример КОДА ИСТОЧНИКА - DRAG-DROP _part
Пример с RENDERing & createObjectURL() с использованием VIDEO.js
PS Я просто хочу улучшить решение " 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!
Ответ 6
Позволяет сделать это легко
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]);
}
}