H5在IOS微信webview中无法校验视频时长问题
因业务需求需要一个图片视频文件上传功能,需支持主流浏览器及微信钉钉内置浏览器,遂考虑用一个简单的H5页面做上传客户端。视频上传因为要控制视频长度,在其他浏览器中都校验通过,但是在微信中却出了问题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| const beforeRead = (file)=> { return new Promise((resolve,reject)=>{ if(props.type == 'video'){ let url = URL.createObjectURL(file) let audioElement = new Audio(url) audioElement.addEventListener("loadedmetadata", ()=>{ let audioDuration = audioElement.duration; if(audioDuration>60){ Toast(`仅支持上传1分钟时长以内视频`) reject() }else{ resolve(file) } }) }else{ if (!['image/jpeg','image/png'].includes(file.type)) { Toast('所选文件格式不支持'); reject() }else{ resolve(file) } } }) }
|
问题原因:IOS微信浏览器需要播放视频才能通过监听loadedmetadata事件获取视频长度,以下是解决办法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| const beforeRead = (file)=> { return new Promise((resolve,reject)=>{ if(props.type == 'video'){ let url = URL.createObjectURL(file) let audioElement = new Audio(url) audioElement.muted = true audioElement.play().then(()=>audioElement.pause()) audioElement.addEventListener("loadedmetadata", ()=>{ let audioDuration = audioElement.duration; if(audioDuration>60){ audioElement.muted = false Toast(`仅支持上传1分钟时长以内视频`) reject() }else{ audioElement.muted = false resolve(file) } }) }else{ if (!['image/jpeg','image/png'].includes(file.type)) { Toast('所选文件格式不支持'); reject() }else{ resolve(file) } } }) }
|
H5页面vue3.0+vant,参见upload组件不再赘述!