<template>
<view class="u-upload" v-if="!disabled">
<view v-if="showUploadList" class="u-list-item u-preview-wrap" v-for="(item, index) in lists" :key="index"
:style="{
width: $u.addUnit(width),
height: $u.addUnit(height)
}">
<view v-if="deletable" class="u-delete-icon" @tap.stop="deleteItem(index)" :style="{
background: delBgColor
}">
<u-icon class="u-icon" :name="delIcon" size="20" :color="delColor"></u-icon>
</view>
<u-line-progress v-if="showProgress && item.progress > 0 && !item.error" :show-percent="false" height="16"
class="u-progress" :percent="item.progress"></u-line-progress>
<view @tap.stop="retry(index)" v-if="item.error" class="u-error-btn">点击重试</view>
<image @tap.stop="doPreviewImage(item.url || item.path, index)" class="u-preview-image" v-if="!item.isImage"
:src="item.url || item.path" :mode="imageMode"></image>
</view>
<slot name="file" :file="lists"></slot>
<view style="display: inline-block;" @tap="selectFile" v-if="maxCount > lists.length">
<slot name="addBtn"></slot>
<view v-if="!customBtn" class="u-list-item u-add-wrap" hover-class="u-add-wrap__hover" hover-stay-time="150"
:style="{
width: $u.addUnit(width),
height: $u.addUnit(height)
}">
<u-icon name="plus" class="u-add-btn" size="40"></u-icon>
<view class="u-add-tips">{{ uploadText }}</view>
</view>
</view>
<w-compress ref='wCompress' />
</view>
</template>
<script>
export default {
methods: {
// 选择图片
selectFile() {
if (this.disabled) return;
const {
name = '', maxCount, multiple, maxSize, sizeType, lists, camera, compressed, maxDuration, sourceType
} = this;
let chooseFile = null;
const newMaxCount = maxCount - lists.length;
// 设置为只选择图片的时候使用 chooseImage 来实现
chooseFile = new Promise((resolve, reject) => {
uni.chooseImage({
count: multiple ? (newMaxCount > 9 ? 9 : newMaxCount) : 1,
sourceType: sourceType,
sizeType,
success: resolve,
fail: reject
});
});
chooseFile
.then(res => {
let file = null;
let listOldLength = this.lists.length;
res.tempFiles.map((val, index) => {
// 检查文件后缀是否允许,如果不在this.limitType内,就会返回false
if (!this.checkFileExt(val)) return;
// 如果是非多选,index大于等于1或者超出最大限制数量时,不处理
if (!multiple && index >= 1) return;
if (val.size > maxSize) {
this.$emit('on-oversize', val, this.lists, this.index);
this.showToast('超出允许的文件大小');
} else {
if (maxCount <= lists.length) {
this.$emit('on-exceed', val, this.lists, this.index);
this.showToast('超出最大允许的文件个数');
return;
}
lists.push({
url: val.path,
progress: 0,
error: false,
file: val
});
}
});
// 每次图片选择完,抛出一个事件,并将当前内部选择的图片数组抛出去
this.$emit('on-choose-complete', this.lists, this.index);
if (this.autoUpload) this.uploadFile(listOldLength);
})
.catch(error => {
this.$emit('on-choose-fail', error);
});
},
}
}
</script>
以上是uview 1.x 版本的 u-upload 源码的部分,由此可见手动触发文件选择的方法为
this.$refs.uUpload.selectFile()//uUpload为引用组件时自己设置的ref值