实现思路:上传视频前校验格式以及视频秒数是否在合理范围,是则上传到相对应的服务器上
HTML
<input type="file" id="videoInput" accept="video/*" @change="checkVideoDuration"/>
JS
// 检验格式与市场时长checkVideoDuration() {let that = this;let file = document.getElementById("videoInput").files[0];if (file.type.split("/")[0] !== "video") {this.$toast.fail("请上传视频格式");return;}let video = document.createElement("video");video.preload = "metadata";// 当视频的元数据加载完成后,会触发loadedmetadata事件video.onloadedmetadata = function () {window.URL.revokeObjectURL(video.src);if (video.duration >= 30) {that.upLoadVideo();// 允许上传操作} else {that.$toast.fail("请上传大于30s的视频哦");// 阻止上传操作event.preventDefault();}};video.src = URL.createObjectURL(event.target.files[0]);
}// 上传视频upLoadVideo() {let that = this;if (this.uploadToken) {var input = document.getElementById("videoInput");var file = input.files[0];let formData = new FormData();formData.append("file", file);formData.append("token", this.uploadToken);axios.post("你的服务器地址", formData).then((response) => {that.$toast.success("视频上传成功");}).catch((error) => {that.$toast.fail("上传失败,请重新上传");});}},
在安卓机一切都很正常,但ios手机连loadedmetadata方法都没进入
想到的解决办法是先自动播放后立马暂停,然后回去视频的描述,但是由于微信h5是禁止了视频自动播放的,这方法不可行,最后使用vant插件结合异步操作解决了这个问题
HTML
<van-uploader :after-read="afterRead" :before-read="beforeRead" :file-list="fileList" type="file" accept="video/*"/>
JS
beforeRead(file) {let that = this;if (file.type.split("/")[0] !== "video") {this.$toast.fail("请上传视频格式");return false;}var url = URL.createObjectURL(file);var audioElement = new Audio(url);var result;audioElement.muted = true;audioElement.play().then(() => audioElement.pause());return new Promise((resolve, reject) => {audioElement.addEventListener("loadedmetadata", function () {// 视频时长值的获取要等到这个匿名函数执行完毕才产生result = audioElement.duration; //得到时长为秒,小数,182.36console.log(result);var serce = parseInt(result);if (serce < 30) {that.$toast.fail("视频时长不得低于30秒");reject();} else {that.loadingShow = true;resolve();}});});},// 视频上传后的处理afterRead(file) {let that = this;const { fileList } = this;let formData = new FormData();formData.append("file", file.file);axios.post("接口地址", formData).then((response) => {that.$toast.success("视频上传成功");}).catch((error) => {that.$toast.fail("上传失败,请重新上传");});},