ngx-quill 使用video标签 自定义视频上传
最近接手了一个新项目,使用了ngx-quill,需要添加视频上传的功能。
ngx-quill默认使用的iframe标签,而不是video来表示视频,根据需求需要使用video,故重新定制video embed。
网上基本都是quill或者vue-quill-editor的,没有ngx-quill版本的,故再次记录。
整体上没有什么难度,唯一遇到的困难是如何引入'Quill',尝试了几种方法,也在ngx-quill的github issue里看到作者回复的通过以下方法引入,但都失败了。
import * as Quill from 'quill' //失败的引入方法
最后是在ngx-quill的源码里找到了引入的方法,成功引入。
const Quill = require('quill')
完整的代码
1 /** 2 * 定制video embed 3 */ 4 const Quill = require('quill') 5 const BlockEmbed = Quill.import('blots/block/embed') 6 7 export class SimpleVideo extends BlockEmbed { 8 static create(value) { // 可根据需要添加属性 9 var node = super.create(value); 10 node.setAttribute('src', value); 11 node.setAttribute('width', '100%'); 12 node.setAttribute('controls',"controls"); 13 return node; 14 } 15 16 static value(node) { 17 return node.getAttribute('src'); 18 } 19 }
/** *注册 */
20 SimpleVideo.blotName = 'SimpleVideo'; //使用的名字
21 SimpleVideo.tagName = 'video'; // 对应的html标签
22 SimpleVideo.className = 'ql-video';
Quill.register(SimpleVideo, true)
1 /** 2 *定制视频上传 3 */ 4 EditorCreated(quill) { const toolbar = quill.getModule('toolbar'); 5 toolbar.addHandler('video', this.videoHandler.bind(this)) } 6 videoHandler() { 7 const that = this; 8 const videoInput = document.createElement('input'); 9 videoInput.setAttribute('type', 'file'); 10 videoInput.setAttribute('accept', 'video/mp4, video/ogg, video/webm'); //对应后缀为mp4,ogv,webm后缀的视频文件 11 videoInput.classList.add('ql-video'); 12 videoInput.addEventListener('change', () => { 13 const file = videoInput.files[0]; 14 const reader = new FileReader(); 15 reader.readAsDataURL(file); 16 reader.onload = function () { 17 // 判断 文件 大小 80M 18 if (file.size / 1024 / 1024 > 80) { 19 console.log('视频大小不超过80Mb'); 20 return; 21 } 22 23 // 判断 长宽比,建议16:9 24 const url = URL.createObjectURL(file) 25 const video = document.createElement('video') 26 video.onloadedmetadata = () => { 27 URL.revokeObjectURL(url) 28 if(video.videoWidth/video.videoHeight > 1.8 || video.videoWidth/video.videoHeight < 1.75){ 29 console.log('建议上传比例接近16:9的视频'); 30 return 31 } 32 const data: FormData = new FormData(); 33 data.append('file', file, file.name); 34 if (videoInput.files != null && videoInput.files[0] != null) { 35 tha.uploadAg('url ', file) // 这里向后台上传了文件,saved为后台返回的视频资源的保存路径 36 .then(saved => { 37 console.log('上传成功', true); 38 const range = that.editor.getSelection(true); 39 that.editor.insertEmbed(range.index, 'SimpleVideo', saved); // 'SimpleVideo'对应blotName属性 40 }); 41 } 42 } 43 video.src = url 44 video.load() 45 }; 46 }); 47 videoInput.click(); 48 }

浙公网安备 33010602011771号