添加本地连接下载,取消仅保存

This commit is contained in:
2026-07-21 14:57:19 +08:00
parent bf9d5f3f22
commit d5d9423599
7 changed files with 601 additions and 535 deletions

View File

@@ -799,8 +799,8 @@
uni.hideLoading();
if (downloadRes.statusCode === 200) {
const tempPath = downloadRes.tempFilePath;
// 下载成功,保存到 yxd 目录
saveFileToYxd(file.name, tempPath);
// 下载成功,直接打开文件
openFile(tempPath);
} else {
uni.showToast({
title: '下载失败',
@@ -826,104 +826,6 @@
}
};
// 将下载的文件保存到外部存储 yxd 目录
const saveFileToYxd = (fileName, tempPath) => {
// #ifdef APP-PLUS
// App 端:复制文件到 /storage/emulated/0/yxd/
const YXD_PATH = '/storage/emulated/0/yxd/';
const ensureYxdDir = (callback) => {
plus.io.resolveLocalFileSystemURL(YXD_PATH, (dirEntry) => {
// 目录已存在
callback(dirEntry);
}, () => {
// 目录不存在,先创建
plus.io.resolveLocalFileSystemURL('/storage/emulated/0/', (rootEntry) => {
rootEntry.getDirectory('yxd', { create: true }, (dirEntry) => {
callback(dirEntry);
}, (err) => {
console.error('创建 yxd 目录失败:', JSON.stringify(err));
uni.showToast({ title: '创建目录失败', icon: 'error' });
openFileConfirm(fileName, tempPath);
});
}, (err) => {
console.error('访问外部存储根目录失败:', JSON.stringify(err));
uni.showToast({ title: '无法访问存储目录', icon: 'error' });
openFileConfirm(fileName, tempPath);
});
});
};
ensureYxdDir((yxdDirEntry) => {
plus.io.resolveLocalFileSystemURL(tempPath, (fileEntry) => {
fileEntry.copyTo(
yxdDirEntry,
fileName,
() => {
const targetPath = YXD_PATH + fileName;
console.log('文件已保存到:', targetPath);
openFileConfirm(fileName, targetPath);
},
(err) => {
console.error('复制文件失败:', JSON.stringify(err));
openFileConfirm(fileName, tempPath);
}
);
}, (err) => {
console.error('读取临时文件失败:', JSON.stringify(err));
openFileConfirm(fileName, tempPath);
});
});
// #endif
// #ifndef APP-PLUS
// 小程序/H5 端:使用 uni.saveFile 保存
uni.saveFile({
tempFilePath: tempPath,
success: (saveRes) => {
openFileConfirm(fileName, saveRes.savedFilePath);
},
fail: () => {
// saveFile 失败则直接确认打开
openFileConfirm(fileName, tempPath);
}
});
// #endif
};
// 下载成功后确认是否打开文件
const openFileConfirm = (fileName, filePath) => {
uni.showActionSheet({
title: `${fileName} 下载完成`,
itemList: ['打开文件', '选择其他应用打开', '仅保存'],
success: (res) => {
switch (res.tapIndex) {
case 0:
// 打开文件(系统默认应用)
openFile(filePath);
break;
case 1:
// 选择其他应用打开showMenu 会弹出分享/打开方式菜单)
openFileWithMenu(filePath);
break;
case 2:
// 仅保存,不打开
uni.showToast({
title: '文件已保存到 yxd 目录',
icon: 'success'
});
break;
}
},
fail: () => {
// 用户取消,默认不打开
uni.showToast({
title: '文件已保存到 yxd 目录',
icon: 'success'
});
}
});
};
// 使用系统默认应用打开
const openFile = (filePath) => {
uni.openDocument({