写个项目,要求要本地上传音视频至服务器,再回显可播放。
当前项目使用了elementUI+Vue
上传图片,请求接口,将图片或者音频文件提交给后台,后台返回存储图片或者音频的ID,由于后台存到mogondb里面了,因此返回的是ID,若是存到服务器里面,返回的就是图片或者是音频存到服务器的地址。回显图片的方式是,先请求接口,根据图片的ID,请求接口图片或者是音频返回的内容,请求接口返回的内容为一个图片或者是音频。
图片以下:html
页面显示的内容:ios
由于接口都是直接返回图片和音频,因此你不能用get请求,只能直接拼接到标签后边。mongodb
图片回显代码以下:axios
<template> <el-upload class="avatar-uploader" :action="fileurl" :data="file" :show-file-list="false" :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess" :on-error="handleAvatarError"> <img v-if="imageUrl" :src="imageUrl" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </template> <script> import api from '../../../../../../utils/env.js'; export default { name:'', props:[], components:{ }, data(){ return{ 'iconid':'123' 'fileurl':api+"/mongodbfile/uploadtomongo", //上传图片的接口地址 'file': { 'file': '' }, // 上传图片传递的参数 'imageUrl': '', //回显的图片的URL } }, computed:{ }, created(){ }, mounted(){ if('新建活动'){ console.log('新建不调用回显图片接口'); }else{ console.log('编辑活动须要调用图片接口'); } }, methods:{ // 编辑页面调用图片回显接口 getUrlParams() { //自定义图片编辑回显的接口和iconid动态ID this.imageUrl = api+'/mongodbfile/downloadfromMongo?id='+this.iconid; }, //上传文件校验 beforeAvatarUpload(file) { const isJPG = file.type; var isFlag = false; if (isJPG=='image/jpeg'||isJPG=='image/png') { isFlag=true; }else{ this.$message.error('上传头像图片只能是 JPG | PNG 格式!'); isFlag=false; } //console.log(isJPG||isPNG); return isFlag; }, //上传图片成功 handleAvatarSuccess(res, file) { //console.log(res); if(res.flag=='true'){ this.imageUrl = URL.createObjectURL(file.raw); //图片上传成功以后,从新给iconid 赋值 this.iconid = res.data; }else{ this.$message.error(res.mes); } }, //上传图片失败 handleAvatarError(res, file){ this.$message.error('上传失败!'); }, }, watch:{ } } </script> <style scoped> </style>
Vue音频动态加载踩到的坑,回显音频的时候也是和回显图片同样的方法,可是音频的资源没有加载进来,一直没有声音,最后使用了动态拼接音频标签的方法,将音频文件加载进来了。
代码以下:api
<template> <div id="zomain"> </div> </template> <script> import api from '../../../utils/env.js'; import axios from 'axios'; export default { name:'', components:{ }, data(){ return{ } }, filters:{ }, created(){ }, mounted(){ }, methods:{ init(){ this.musicSrc = api + '/mongodbfile/downloadfromMongo?id='+soundid; let audioDom = "<audio id='zo-audio' loop='loop' autoplay>"+ "<source id='audioSource' src='"+ this.musicSrc +"' type='audio/mp3'>"+ "</audio>"; $('#zomain').append(audioDom); //苹果手机音频兼容性 document.addEventListener("WeixinJSBridgeReady", function () { $('#zo-audio').get(0).play(); }, false); } } } </script> <style scoped> </style>