先上一段js获取视频时长的代码
getVideoDuration(file) {
var url = URL.createObjectURL(file);
var audioElement = new Audio(url);
var self = this;
var result;
audioElement.addEventListener("loadedmetadata", function() {
// 视频时长值的获取要等到这个匿名函数执行完毕才产生
result = audioElement.duration; //得到时长为秒,小数,182.36
});
}
由于是在监听的回调函数里拿到了当前视频的时长信息,所以需要封装为返回promose的方法供其他方法调用,又因before-upload方法不支持用async 修饰,所以通过返回的promise被reject来阻止上传
// 获取视频时长
getVideoDuration(file) {
return new Promise(function(resolve, reject) {
//做一些异步操作
let url = URL.createObjectURL(file)
let audioElement = new Audio(url)
let duration = 0
audioElement.addEventListener('loadedmetadata', function() {
duration = audioElement.duration //时长为秒,小数,182.36
resolve(duration)
})
console.log(reject)
})
},
完整代码如下:
html部分
<el-form-item label="上传视频:" prop="video">
<el-upload
class="upload-demo"
:action="uploadUrl"
:on-remove="handleVideoRemove"
multiple
:limit="1"
:on-exceed="handleVideoExceed"
:on-success="handleVideoUploadSuccess"
:on-error="handleVideoUploadError"
:before-upload="handleBeforeUpload"
:file-list="videoList"
>
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">
请上传时长小于1小时,大小不超过50M的视频,支持mp4格式
</div>
</el-upload>
</el-form-item>
js部分
methods: {
// 获取视频时长
getVideoDuration(file) {
return new Promise(function(resolve, reject) {
//做一些异步操作
let url = URL.createObjectURL(file)
let audioElement = new Audio(url)
let duration = 0
audioElement.addEventListener('loadedmetadata', function() {
duration = audioElement.duration //时长为秒,小数,182.36
resolve(duration)
})
console.log(reject)
})
},
handleBeforeUpload(file) {
return new Promise(async (resolve, reject) => {
if (!this.isVideo(file.name)) {
this.$message.warning('仅支持mp4格式')
return reject()
}
// 大小不能超过50M
if (file.size > 1024 * 1024 * 50) {
this.$message.warning('文件大小不能超过50M')
return reject()
}
let duration = await this.getVideoDuration(file)
if (duration / 3600 >= 1) {
this.$message.warning('请上传时长小于1小时的视频')
return reject()
} else {
this.isDisabled = true
this.loading = true
resolve()
}
})
}}