功能背景
泛微 E10 支持单附件字段的批量下载能力。但默认情况下,用户只能逐个字段进行批量下载附件,当表单包含大量附件字段时,操作效率较低。通过开发批量下载功能,提升用户体验。
技术实现方案
下面是实现批量下载功能的核心代码,主要分为三个步骤:收集附件 ID、创建异步下载任务、轮询检查任务状态并下载:
// 初始化 SDK 实例
const weFormSdk = window.WeFormSDK.getWeFormInstance();
// 定义需要下载附件的字段名称,请修改为对应的主表字段名称
const fieldNames = [
"sigvendatf",
"poa",
"regcer",
"taxcer",
"pscq",
"pscend",
"bancon",
"conpo",
"emaappandc"
];
// 收集所有附件 ID
const values = [];
fieldNames.forEach(fieldName => {
try {
const fieldId = weFormSdk.convertFieldNameToId(fieldName);
const fieldValue = weFormSdk.getFieldValue(fieldId);
if (fieldValue) {
values.push(fieldValue);
}
} catch (error) {
console.error(` 获取字段 ${fieldName} 失败:`, error);
}
});
// 创建异步下载任务
async function createDownloadTask() {
if (values.length === 0) {
window.WeFormSDK.showMessage("没有可下载的文件", 1, 3);
return;
}
const today = new Date().toISOString().split('T')[0]; // 获取当前日期
try {
const response = await fetch('/api/file/batch/asynchronous/downloadByFileIds', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
"module": "ebuildercard",
"fileIds": values.join(','),
"authModule": "ebuildercard",
"source": "form",
"zipName": `附件名称在这里-请修改或赋值变量-${today}`
})
});
const data = await response.json();
if (!data.data.taskId) {
throw new Error('获取任务 ID 失败');
}
window.WeFormSDK.showMessage("开始创建下载任务", 3, 2);
await checkDownloadStatus(data.data.taskId);
} catch (error) {
console.error('创建下载任务失败:', error);
window.WeFormSDK.showMessage("创建下载任务失败", 2, 3);
}
}
// 轮询检查下载任务状态
async function checkDownloadStatus(taskId) {
let attempt = 0;
const maxAttempts = 20; // 最多尝试 20 次
while (attempt < maxAttempts) {
try {
const response = await fetch(`/api/file/batchDownloadPercent?uuid=${taskId}`);
const data = await response.json();
if (data.data.fileId) {
window.WeFormSDK.showMessage("下载任务已完成", 3, 2);
downloadFile(data.data.fileId);
return;
}
attempt++;
if (attempt < maxAttempts) {
await new Promise(resolve => setTimeout(resolve, 500)); // 等待 500ms
}
} catch (error) {
console.error('查询下载状态失败:', error);
throw error;
}
}
throw new Error('下载任务超时');
}
// 执行文件下载
function downloadFile(fileId) {
const link = document.createElement('a');
link.href = `/api/file/remotedownload/${fileId}/upload/true`;
link.setAttribute('download', '');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
// 启动下载流程
createDownloadTask().catch(error => {
console.error('下载流程出错:', error);
window.WeFormSDK.showMessage("下载过程中出现错误", 2, 3);
});
代码功能解析
附件收集模块
- 通过
weFormSdk.convertFieldNameToId
方法将字段名称转换为系统 ID - 使用
weFormSdk.getFieldValue
获取附件 ID 值 - 支持从多个字段收集附件,适应复杂表单结构
- 通过
异步下载任务创建
- 调用平台提供的
/api/file/batch/asynchronous/downloadByFileIds
接口 - 将所有附件 ID 合并后作为参数传递
- 支持自定义 ZIP 文件名,自动添加日期戳
- 调用平台提供的
任务状态监控机制
- 通过轮询
/api/file/batchDownloadPercent
接口检查进度 - 设置最大尝试次数和间隔时间,防止无限循环
- 任务完成后自动触发下载
- 通过轮询
用户体验优化
- 使用平台 SDK 提供的消息提示功能
- 完整的错误处理机制
- 异步操作避免界面卡顿
[泛微 E10] 批量下载当前表单内所有附件 by https://oneszhang.com/archives/164.html