模板代码:
<el-upload
v-loading="officeVideoLoading "
accept=".mp4, .webm"
action="#"
:auto-upload="false"
:on-change="onChangeVideo"
:show-file-list="false"
>
<div class="avatar-uploader-imgBox">
<img
v-if="officeVideoCover"
class="avatar"
:src="officeVideoCover"
/>
<div v-else>
<i class="el-icon-upload2"></i>
<div>点击选择视频文件</div>
<div slot="tip" style="color: red">
* 只能上传mp4文件,且不超过50M
</div>
</div>
</div>
</el-upload>
脚本代码
async onChangeVideo(file) {
this.officeVideoLoading = true
const suffix = file.name.split('.').pop().toLowerCase()
const isJPG = suffix === 'webm' || suffix === 'mp4'
const isLt2M = file.size / 1024 / 1024 < 50
if (isJPG && isLt2M) {
const frame = await this.captureFrame(file, 1)
this.createPreview(frame)
this.getBase64(file).then((res) => {
this.officeVideo = res
this.officeVideoLoading = false
})
} else {
this.officeVideoLoading = false
}
},
captureFrame(videoFile, time = 0) {
return new Promise((resolve) => {
const video = document.createElement('video')
video.currentTime = time
video.muted = true
video.autoplay = true
video.oncanplay = async () => {
const frame = await this.drawVideo(video)
resolve(frame)
}
video.src = URL.createObjectURL(videoFile.raw)
})
},
drawVideo(video) {
return new Promise((resolve) => {
const cvs = document.createElement('canvas')
const ctx = cvs.getContext('2d')
ctx.drawImage(video, 0, 0, cvs.width, cvs.height)
cvs.toBlob((blob) => {
resolve({
blob,
url: URL.createObjectURL(blob),
})
})
})
},
createPreview(frame) {
function blobToBase64(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.readAsDataURL(blob)
reader.onloadend = () => {
resolve(reader.result)
}
reader.onerror = (error) => {
reject(error)
}
})
}
blobToBase64(frame.blob).then((res) => {
this.officeVideoCover = res
})
},
getBase64(file) {
return new Promise((resolve, reject) => {
let reader = new FileReader()
let fileResult = ''
reader.readAsDataURL(file.raw)
reader.onload = function () {
fileResult = reader.result
}
reader.onerror = function (error) {
reject(error)
}
reader.onloadend = function () {
resolve(fileResult)
}
})
},