uniapp实现图片、视频上传
文章目录
相关文档:
- 结合
uView
插件 +uni.uploadFile
实现
u-upload
uploadfile
效果图
组件
- 简单封装,还有很多属性…,自定义样式等…根据个人所需调整
template
<template>
<view>
<u-upload
:fileList="fileList"
@afterRead="afterRead"
@delete="deletePic"
name="files"
:maxCount="maxCount"
:multiple="multiple"
:width="width"
:height="height"
:previewFullImage="previewFullImage"
:accept="accept"
>
</u-upload>
</view>
</template>
js
- toast 方法,修改为自己即可;
<script>
export default {
name:"uploadFile",
props: {
width: {
type: Number,
default: 60
},
height: {
type: Number,
default: 60
},
maxCount: { // 限制上传数量
type: Number,
default: 1
},
multiple: { // 是否开启图片多选
type: Boolean,
default: false
},
list: { // 图片列表
type: Array,
default: []
},
previewFullImage: { // 文件预览
type: Boolean,
default: true
},
accept: { // 上传类型 all | media | image | file | video
type: String,
default: image
}
},
data() {
return {
fileList: []
};
},
mounted() {
this.fileList = this.list;
},
methods: {
/**
* 删除图片
* @param {Object} event
*/
deletePic(event) {
this.fileList.splice(event.index, 1)
},
/**
* 读取后的处理函数
* @param {Object} event
*/
async afterRead(event) {
let lists = [].concat(event.file)
let fileListLen =this.fileList.length
lists.map((item) => {
this.fileList.push({
...item,
status: 'uploading',
message: '上传中...'
})
})
for (let i = 0; i < lists.length; i++) {
const result = await this.uploadFilePromise(lists[i].url)
this.$util.showToast('上传成功');
let item = this.fileList[fileListLen]
this.fileList.splice(fileListLen, 1, Object.assign(item, {
status: 'success',
message: '',
url: result.imgUrl
}))
fileListLen++
}
},
/**
* 上传图片
* @param {Object} url
*/
uploadFilePromise(url) {
return new Promise((resolve, reject) => {
uni.uploadFile({
url: `服务器 url xxxx`,
filePath: url,
name: 'file', // 文件对应的 key
header: {
// 根据个人所需,是否要登录
// Authorization: `Bearer ${ getToken() }`
},
success: (res) => {
// 接口返回数据,自行修改
let datas = JSON.parse(res.data);
if (datas.code != 200) {
this.$util.showToast(datas.msg);
reject(res);
return;
}
setTimeout(() => {
resolve(datas.data)
}, 1000)
},
fail: (res) => {
reject(res);
}
});
})
}
}
}
</script>
<style>
</style>
使用
<view>
<uploadFile :list="imgList"></uploadFile>
</view>
import uploadFile from '@/components/uploadFile/uploadFile.vue'
export default {
components: {
uploadFile
},
data() {
return {
imgList: [{ url: 'https://cdn.uviewui.com/uview/swiper/1.jpg' }] // test 根据业务处理
}
}
}
}
标签:uniapp,uploadFile,default,微信,APP,fileList,url,type,event
From: https://blog.csdn.net/Smile_ping/article/details/139326329