在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