0%
Demo
文件上传预览
代码
HTML
<form action=""> <fieldset> <legend>上传视频文件</legend> <input type="file" accept="video/*"> <h3>视频预览</h3> <video id="video" src="" controls></video> </fieldset> <fieldset> <legend>上传图片文件</legend> <input type="file" accept="image/*"> <h3>图片预览</h3> <img id="img" src="" alt=""> </fieldset> </form>
|
CSS
video, img { width: 300px; }
|
JS
let form = document.querySelector('form') let videoEl = document.getElementById('video') let imgEl = document.getElementById('img') form.addEventListener('change', event => { if(event.target.type === 'file') { let file = event.target.files[0] if(event.target.accept.indexOf('video') >= 0) { videoEl.src = getObjectURL(file) }else if(event.target.accept.indexOf('image') >= 0) { imgEl.src = getObjectURL(file) } } }) let getObjectURL = file => { let url = '' if (window.createObjectURL != undefined) { url = window.createObjectURL(file); } else if (window.URL != undefined) { url = window.URL.createObjectURL(file); } else if (window.webkitURL != undefined) { url = window.webkitURL.createObjectURL(file); } return url }
|