效果图
html
<template>
<view>
<view class="uploadImage">
<view v-for="(item, index) in viList" class="aa" :key="index">
<view class="del" @click="delHandler(index)">删除</view>
<view v-if="item.type === 'v'" class="typeBox">视频格式</view>
<image class="sty" :src="item.image" @click="previewImageHandler(item.type)" mode="scaleToFill" />
</view>
</view>
<view @click="chooseVideoHandler('video')" class="flexC btnBox">上传视频</view>
<view @click="chooseVideoHandler('image')" class="flexC btnBox">上传图片</view>
</view>
</template>
js
<script>
export default {
data() {
return {
viList: [],
vue_uploadAction: '上传接口',
}
},
methods: {
async chooseVideoHandler(state) {
uni.showLoading({
mask: true,
title: '上传中...',
})
let uploadFile = ''
// 1.选择要上传的视频
const res = await uni.chooseMedia({
maxDuration: 60,
sourceType: ['album'],
mediaType: Array(state),
})
// 判断函数传来的类型是不是视频 如果是就使用视频缩略图 => thumbTempFilePath
uploadFile = state == 'video' ? res[1].tempFiles[0].thumbTempFilePath : res[1].tempFiles[0].tempFilePath
var that = this
const arr = await uni.uploadFile({
// 需要上传的地址
url: that.vue_uploadAction,
// filePath 需要上传的文件
filePath: uploadFile,
name: 'file',
// header: {
// token: that.vuex_token // 挂载请求头为用户的 token
// },
})
let data = JSON.parse(arr[1].data)
console.log('data:', data)
if (data.code !== 1) {
// 视频上传失败了
uni.hideLoading()
uni.showToast({
title: data.msg,
icon: 'none',
})
return
}
// 上传成功(把上传成功后的文件路径 push 到页面需要显示的视频数据列表中)
this.viList.push({
image: data.data.fullurl,
type: state == 'video' ? 'v' : 'i',
})
uni.hideLoading()
},
previewImageHandler(type) {
type === 'i' &&
uni.previewImage({
urls: this.viList.filter(t => t.type === 'i').map(t => t.image),
})
},
delHandler(index) {
this.viList.splice(index, 1)
},
},
}
</script>
css
<style lang="less">
.uploadImage {
display: flex;
flex-wrap: wrap;
}
.aa {
position: relative;
> .del {
position: absolute;
top: 0;
left: 0;
z-index: 999;
color: #fff;
font-size: 26rpx;
}
> .sty {
width: 250rpx;
height: 250rpx;
}
> .jinzhi {
width: 250rpx;
height: 250rpx;
background: transparent;
position: absolute;
z-index: 998;
top: 0;
left: 0;
}
}
.typeBox {
color: aqua;
position: absolute;
top: 0;
right: 0;
font-size: 26rpx;
}
.btnBox {
margin: 0 auto;
width: 240rpx;
height: 80rpx;
margin-top: 20rpx;
background: #dcbbaa;
color: #000;
}
</style>