转至:http://www.bcty365.com/content-69-6242-1.html
项目要求:
input file 上传mp4视频,限制时长超过1分钟。
先声明几个id
var filesId = document.getElementById('files');//获取id
var videoId = document.getElementById('videoId');
1、先去拿 input file 上传的 mp4视频的 本地路径;
由于浏览器的安全限制,用户上传文件的时候,不允许看到本地路径的,但,这样就可以取到 本地路径。
function getFileURL(file) {
var getUrl = null;
if (window.createObjectURL != undefined) { // basic
getUrl = window.createObjectURL(file);
} else if (window.URL != undefined) { // mozilla(firefox)
getUrl = window.URL.createObjectURL(file);
} else if (window.webkitURL != undefined) { // webkit or chrome
getUrl = window.webkitURL.createObjectURL(file);
}
return getUrl;
}
2、再去把获取到的本地路径赋值给 video 的 src;
var selectFile = function(){
var url = getFileURL(this.files[0]);//把当前的 files[0] 传进去
if (url) {
videoId.src = url;
}
}
filesId.addEventListener('change', selectFile);//监听 change 事件,当 input file 发生变化的时候执行
3、直接获取 video 的duration,限制时长超1分钟。
如果确认 video 赋值了并且拿不到 duration ,设置一个延时就好了。 setTimeout(function(){ ... },1000)
var duration = videoId.duration;
if (Math.floor(duration) > 60) {
alert('视频不能大于60秒');
}
可以了。