Use js in Vue to realize video preview, picture preview and text preview

The effect is as shown in the figure:

 

1. First we are in the template:
  <div v-if="textUrl" class="imgPreview">
    {
  
  { textUrl }}
  </div>
  <div v-if="videoUrl" class="imgPreview">
    <video alt="" style="width:300px;height:300px" controls>
      <source :src="videoUrl" type="video/mp4">
      <source :src="videoUrl" type="video/ogg">
    </video>
  </div>
  <div  v-if="photoUrl"  class="imgPreview">
    <img :src="photoUrl" alt="" style="width:300px;height:300px">
  </div>
</div>

Here, v-if is used to display different effects:

2. The method is as follows:

getAccessData(absolutePath,index) {
  this.picListIndex = index
  this.currentPicPath = absolutePath //path
  let picIndex = absolutePath.lastIndexOf('.');
  this.ext = absolutePath.substr(picIndex + 1);//file type
  let param = new FormData();
  param.append('file', absolutePath);
  if (this.ext == 'jpg' || this.ext == 'png' || this.ext == 'gif' || this.ext == 'jpeg') {
//Corresponding to your own file service interface, optimistic about the parameters
    getFilePhoto(this.$route.query.token,param).then(res => {  、、
      let _this = this
      let blob = new Blob([res.data])
      var reader = new window.FileReader();
      reader.readAsDataURL(blob);
      reader.onloadend = function (e) {
        _this.photoUrl = e.target.result
        _this.textUrl= '';
        _this.videoUrl= '';
        console.log(_this.photoUrl)
      }
    })
  }
  if (this.ext == 'mp4' || this.ext == 'avi' || this.ext == 'rmvb' || this.ext == 'rm' || this.ext == 'flv') {
//Corresponding to your own file service interface, optimistic about the parameters
    getFilePhoto(this.$route.query.token,param).then(res => { 
      let _this = this
      let blob = new Blob([res.data],{type:'video/mp4'})
      var reader = new window.FileReader();
      reader.readAsDataURL(blob);
      reader.onloadend = function (e) {
        _this.videoUrl = e.target.result
        _this.textUrl= '';
        _this.photoUrl= '';
      }
    })
  }
  if (this.ext == 'txt' ||this. ext == 'doc' || this.ext == 'docx' || this.ext == 'xls' || this.ext == 'xlsx' || this.ext == 'pdf') {
//Corresponding to your own file service interface, optimistic about the parameters
    getFilePhoto(this.$route.query.token,param).then(res => {
      let _this = this
      let blob = new Blob([res.data])
      var reader = new window.FileReader();
      reader.readAsText(blob,'utf-8');
      reader.onloadend = function (e) {
        _this.textUrl = e.target.result
        _this.photoUrl= '';
        _this.videoUrl= '';
        console.log(_this.textUrl)
      }
    })
  }
}

Some details: the initial definition in data is convenient for global calls.

The format of the parameters in the interface:

 

Guess you like

Origin blog.csdn.net/hanshilong100/article/details/127746172