一、上传到OSS或者服务器
缺点:
1.大文件上传时间过长
2.如果用户只是预览则会浪费服务端存储
二、使用FileReader对象转换File对象为base64
<input type="file" id="videoInput"><video src="" alt="预览" id="video" controls="controls"><script> const videoInput = document.getElementById('videoInput'); videoInput.addEventListener('change', e => { previewByReader(e.target.files[0]) })function fileToBase64(file: File): Promise<{ url: any, filename: string }> { const fileReader = new FileReader() fileReader.readAsDataURL(file) var filename = file.name; return new Promise((resolve, reject) => { fileReader.addEventListener("loadend", (e: ProgressEvent<FileReader>) => { var url: any = e.target!.result; resolve({ url, filename }) }, false); })} async function previewByReader (file) { const {url} = await fileToBase64(file) video.src = url }</script>
三、通过blob协议实现预览
<input type="file" id="videoInput"> <video src="" alt="预览" id="video" controls="controls" width="400" height="200"> <script> const videoInput = document.getElementById('videoInput'); videoInput.addEventListener('change', e => { previewByURL(e.target.files[0]) }) function previewByURL (file) { video.src = URL.createObjectURL(file) } </script>