話不多說貼上代碼
<template>
<div>
<!-- <input type="file" accept="image/*" @change="loadFile">
<img id="file" width="480" height="270" v-show="showImg"/> -->
<input type="file" accept="video/*" @change="loadFile">
<video id="file" width="480" height="270" v-show="showVideo" controls/>
</div>
</template>
<script>
export default {
data(){
return {
showImg:false
showVideo:false
}
},
methods:{
loadFile(event){
const reader = new FileReader();
const that = this
//如果是SSR渲染需要加上如下判斷(比如nuxt)
if(!process.browser)return
reader.onload = function(){
const output = document.querySelector("#file")
that.showVideo = true;
output.src = URL.createObjectURL(new Blob([reader.result]))
}
reader.readAsArrayBuffer(event.target.files[0])
}
}
}
</script>
主要利用 URL.createObjectURL()方法來實現。URL.createObjectURL()會創建 DOMString。其中包含一個表示參數中給出的對象的URL。這個URL的生命周期和創建它的窗口中的document綁定。這個新的URL對象表示指定的file對象或者blob對象。