微信H5界面使用uni-file-picker上传文件或图片时,上传多张图片或文件失败。经过各种探索与思考,我觉得决定自己写一个兼容安卓、ios以及各种浏览器的上传文件组件
思路:根据uni.getSystemInfo判断是ios还是android,然后通过navigator.userAgent.toLowerCase()判断使用的是那种浏览器。
使用微信浏览器每次只能够上传一张图片或文件,综合代码如下:
<template>
<view class="">
<view :class="[!disabled ? 'btn-list' : 'btn-list-disabled' , 'btns', 'mbottom12']" @click="uploadFile">
点击上传文件
</view>
<view class="file-list colorMain" v-for="item in fileList" :key="item.uid">
<view class="file-name" @click="lookMessage(item)">
{{item.name}}
</view>
<view @click="deleteFileList(item)" v-if="!disabled">
<uni-icons color="#888888" type="trash" size="20"></uni-icons>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
fileList: [],
}
},
props: {
disabled: {
type: Boolean,
defalut: false
}
},
methods: {
// 初始化文件
initData (fj) {
let fileList = fj
this.fileList = fileList.map(item => {
return {
url: item.url,
name: item.name,
extname: item.name.slice(item.name.lastIndexOf('.')+1),
uid: item.uid
}
})
},
// 判断是微信浏览器,还是其它浏览器 true:微信浏览器 false:其他浏览器
comIsShowBanner() {
return new Promise(resolve => {
let target = navigator.userAgent.toLowerCase(),
isWeixin = target.indexOf('micromessenger'),
status = false
if (isWeixin !== -1) status = true
//判断是安卓还是ios,安卓的微信用 chooseImage, 其余的用 chooseFile
uni.getSystemInfo({
success: function (res) {
console.log(res)
if (res.osName === 'android' && status) {
resolve(true)
} else {
resolve(false)
}
}
})
})
},
uploadFile () {
if (this.disabled) return
this.comIsShowBanner().then(resolve => {
// 微信浏览器
if (resolve) {
uni.chooseImage({
count: 1, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album'], //从相册选择
success: (res) =>{
this.selectFileList(res)
console.log(JSON.stringify(res.tempFilePaths));
}
})
} else {
uni.chooseFile({
success: (res) => {
// tempFilePath可以作为img标签的src属性显示图片
console.log(res)
this.selectFileList(res)
}
})
}
})
},
// 选择文件、并上传附件
selectFileList (e) {
let fileList = []
e.tempFiles.forEach(item => {
this.$utils.uploadFile(item.path).then(res => {
let msg = res.msg
fileList.push({
url: window.fileUrl + msg,
name: `${item.name}`,
extname: `${item.type}`,
uid: item.lastModified
})
if (fileList.length === e.tempFiles.length) {
this.fileList = this.fileList.concat(fileList)
}
})
})
},
// 删除某一个附件
deleteFileList (e) {
this.fileList = this.fileList.filter(item => {
if (item.uid !== e.uid) return item
})
},
// 查看文件详情
lookMessage (item) {
window.open(item.url)
}
}
}
</script>
<style lang="scss" scoped>
.btns {
padding: 18upx;
}
.file-list {
padding: 12upx 0;
display: flex;
align-items: center;
justify-content: space-between;
.file-name {
width: 86%;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
}
</style>