使用vant的uploader 组件上传视频或图片,
/*
预先浏览显示
*/
<div v-for="(file,v) in mediaList"
:key="v"
@click="delImg(v)"
class="videoItem">
<div v-if="type ==='0' ">
<div class="imgItem">
<div class="deleteIcon">
<van-icon name="close"size="20"></van-icon>
</div>
<div>
<img :src="file.content" alt=""width="100" height="100">
</div>
</div>
</div>
<div v-if="type ==='1'">
<div class="imgItem">
<div>
<video :src="file.content" controls="controls"width="100" height="100px"></video>
</div>
<div class="deleteIcon">
<van-icon name="close"size="20"></van-icon>
</div>
</div>
</div>
</div>
/*上传按钮*/
<div class="uploadItem
text-center-pk">
<div >
<van-uploader v-model="upLoadFile" :preview-image="false" :max-count="5" :after-read="afterRead" accept="*">
</van-uploader>
</div>
<div class="chooseFile text-light-pk">选择素材 </div>
</div>
Script:
return{
mediaList:[],
upLoadFile:[],
type:"",//0 图片 1:视频
}
methods:{
afterRead(file){
this.$toast.loading()
if(this.mediaList.length===0){
this.type="";
}
//单个文件
let fileType= null;
if(file.file.type.indexOf( 'image') !== -1) {
fileType = "image";
}
if(file.file.type.indexOf( 'video') !== -1) {
fileType = "video";
}
if(!fileType) {
this.$toast.fail("请上传图片或者视频");
return
}
fileType = fileType === "image"? "0" : "1";
if(this.type=== "") {
this.type = fileType;
}
else {
if(this.type!= fileType) {
this.$toast.fail("只能一种格式");
return;
}
}
this.mediaList.push(file);
//此时,可以将文件上传
this.upLoadFiles();
},
upLoadFiles(){
if(this.mediaList.length>0){
for (let i = 0; i < this.mediaList.length; i++) {
this.formData.append('files', this.mediaList[i].file);
}
//例如接口是:imageFile
this.$api.imageFile (this.formData).then(res=>{
let result=this.$resData(res)
if(res.status==200){
this.$toast.loading({
message:"上传成功"
})
}
})
}
else{
this.$toast.loading({
message:"请上传素材"
})
}
},
// 删除指定下标的图片对象
delImg(index) {
if (isNaN(index) || index >= this.mediaList.length) {
return false
}
let tmp = [];
for (let i = 0, len = this.mediaList.length; i < len; i++) {
if (this.mediaList[i] !== this.mediaList[index]) {
tmp.push(this.mediaList[i])
}
}
this.mediaList = tmp;
this.upLoadFile=this.mediaList
},
}