话 不多说,直接上代码:
<!-- 上传文件(自定义文件类型) -->
<template>
<view>
<view @click="handleUploadFile()" v-if="uploadedFiles.length == 0" >
<u-upload disabled uploadIcon="plus" width="80rpx" height="80rpx"></u-upload>
</view>
<view v-for="(file, index) in uploadedFiles" :key="index" @click="previewFile(file)">
{{ file.name }}
</view>
<u-toast ref="uToast"></u-toast>
</view>
</template>
<script>
export default {
components: {},
props: {
//接受的附件格式
types: {
type: String,
default: () => '.png,.jpg,.jpeg,.pdf,.doc,.docx,.xls,.xlsx',
},
//最多上传几个文件
maxFile: {
type: Number,
default: 5,
},
},
data() {
return {
uploadedFiles: [], // 用于存储上传的文件信息
};
},
methods: {
async handleUploadFile() {
const types = this.types.split(',');
try {
const res = await wx.chooseMessageFile({
count: this.maxFile,
extension: types,
});
const files = res.tempFiles;
const processResultFiles = async () => {
const promises = files.map(async (v) => {
return await this.asyncResultFiles(v);
});
return await Promise.all(promises);
};
const processArr = await processResultFiles();
// 更新 uploadedFiles 状态
this.uploadedFiles = processArr.map(item => ({
name: files[0].name,
url: item,
// 其他需要的信息
}));
} catch (err) {
console.error("上传文件过程中出错:", err);
// 处理错误
}
},
//异步配合Promise.all可以一次性拿到最终的结果
asyncResultFiles(item) {
return new Promise(async (resolve) => {
const result = await this.uploadFilePromise(item.path);
const res = JSON.parse(result);
if (res.code == 200) {
resolve(res.data);
}
});
},
//异步返回接口的结果
uploadFilePromise(filePath) {
return new Promise((resolve, reject) => {
uni.uploadFile({
url: `替换成你的服务器地址`,
filePath: filePath,
name: 'file',
header: {
'token': uni.getStorageSync('uuid'),
},
success: (res) => {
resolve(res.data);
},
fail: (err) => {
reject(err);
},
});
});
},
previewFile(item) {
uni.showLoading({
title: '文件打开中',
mask: true
});
// 预览网络文档
wx.downloadFile({
url: item.url, // 文件的本身url
filePath: wx.env.USER_DATA_PATH + '/' + item.name, // 本地自定义的文件名
success: function (res) {
let filePath = res.filePath; // 微信临时文件路径(这里要使用自定义的名字文件名,否则打开的文件名是乱码)
wx.openDocument({
filePath: filePath,
showMenu: true, // 是否显示右上角菜单按钮 默认为false(看自身需求,可要可不要。后期涉及到右上角分享功能)
success: function () {
// this.$refs.uToast.show('打开文件成功')
},
fail: function() {
// this.$refs.uToast.show('打开文件失败,请稍后重试')
}
});
uni.hideLoading();
},
fail: function() {
// this.$refs.uToast.show('打开文件失败,请稍后重试')
uni.hideLoading();
}
});
}
},
};
</script>
<style scoped lang="scss">
</style>