在vue中如何實現上傳本地視頻和圖片預覽


話不多說貼上代碼

<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對象。

參考自全棧修仙之路-前端進階篇


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM