效果如图:
1.首先我们在模板里:
<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>
这里通过v-if来显示不同的效果:
2.方法如下:
getAccessData(absolutePath,index) { this.picListIndex = index this.currentPicPath = absolutePath //路径 let picIndex = absolutePath.lastIndexOf('.'); this.ext = absolutePath.substr(picIndex + 1);//文件类型 let param = new FormData(); param.append('file', absolutePath); if (this.ext == 'jpg' || this.ext == 'png' || this.ext == 'gif' || this.ext == 'jpeg') { //对应自己的文件服务接口,看好参数 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') { //对应自己的文件服务接口,看好参数 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') { //对应自己的文件服务接口,看好参数 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) } }) } }
一些细节:data里边的初始定义,方便全局调用。
接口里边参数的格式: