问题描述:
uni-file-picker中v-model绑定的fileList并不会回显失败的文件,导致我们获取的fileList不一致。无法准确控制文件上传数量limit。
解决方法:
<uni-file-picker v-model="fileList" :limit="limit" :auto-upload="false" file-mediatype="all" @select="handleBeforeUpload"></uni-file-picker>
<script setup lang="ts">
const fileList = ref([]);
/**
* 自定义图片上传
*
* @param params
*/
async function handleUpload(options : any) : Promise<any> {
// 上传API调用
const { data: fileInfo } = await uploadFileApi(options.file);
const index = fileList.value.findIndex((item) => item.uuid == options.uuid);
const obj = {
url: fileInfo,
extname: "",
name: options.file.name,
}
//替换回显列表文件
fileList.value.splice(index, 1, obj);
}
/**
* 限制用户上传文件的格式和大小
*/
async function handleBeforeUpload(event : any) {
// 过滤掉size大于5mb的数据(这步很关键)
let tempFiles = event.tempFiles.filter((item) => item.size < props.maxSize * 1048 * 1048);
tempFiles.length < event.tempFiles.length ? msg('上传文件不能大于' + props.maxSize + 'M') : '';
var suffix = '';
const list = tempFiles.filter((item) => {
suffix = item.name.substring(item.name.lastIndexOf('.') + 1);
return props.suffixArray.indexOf(suffix) > -1 && props.suffixArray.length > 0
})
list.length < tempFiles.length ? msg('表单不支持文件格式:' + suffix) : '';
if (fileList.value.length > 0 && list.length === 0) {
console.log('没有合规项且之前已有添加')
fileList.value = fileList.value.slice(0, fileList.value.length);
return // 本次添加没有合规的图片如果后续要发请求可直接return
} else if (fileList.value.length > 0 && list.length > 0) {
console.log('有合规项且之前已有添加')
fileList.value = fileList.value.concat(list);
} else {
fileList.value = list // 初始值
console.log('之前没有添加')
}
for (let i = 0; i < list.length; i++) {
const file = list[i]
await handleUpload(file)
}
}
</script>