使用vue3+uniapp实现PDF下载并自动打开预览
async function handleSubmit() {
const url = 'http://' + configStore.curServiceIp + ':8999/' + responseData.MajorName
try {
loading.value.open('下载中...');
const downloadTask = uni.downloadFile({
url: url,
success: (res) => {
if (res.statusCode === 200) {
uni.saveFile({
tempFilePath: res.tempFilePath,
success: (saveRes) => {
uni.showToast({
title: '文件保存成功',
icon: 'success'
});
console.log('文件保存路径:', saveRes.savedFilePath);
// 打开下载的文件
uni.openDocument({
filePath: saveRes.savedFilePath,
fileType: 'pdf',
success: () => {
console.log('打开文档成功');
},
fail: (err) => {
console.error('打开文档失败:', err);
}
});
},
fail: () => {
uni.showToast({
title: '文件保存失败',
icon: 'none'
});
}
});
}
},
fail: () => {
uni.showToast({
title: '文件下载失败',
icon: 'none'
});
},
complete: () => {
loading.value.close();
}
});
// 监听下载进度
downloadTask.onProgressUpdate((res) => {
console.log('下载进度:', res.progress);
});
} catch (error) {
loading.value.close();
uni.showToast({
title: '下载出错: ' + error.message,
icon: 'none'
});
}
}