<template>
|
<view>
|
<button @click="openExcel()">下载并打开文件</button>
|
</view>
|
</template>
|
|
<script>
|
export default {
|
data() {
|
return {
|
imageUrl: '' ,// 用于存储图片路径
|
fileName:''
|
};
|
},
|
onLoad(options) {
|
//从 URL 参数中获取图片路径
|
if (options.url) {
|
this.imageUrl = options.url;
|
console.log("666" + this.imageUrl)
|
// 从 URL 参数获取原始文件名
|
const originalFileName = options.fileName;
|
|
// 生成时间戳(格式:YYYYMMDDHHMMSS)
|
const now = new Date();
|
const timestamp = [
|
now.getFullYear(),
|
String(now.getMonth() + 1).padStart(2, '0'),
|
String(now.getDate()).padStart(2, '0'),
|
String(now.getHours()).padStart(2, '0'),
|
String(now.getMinutes()).padStart(2, '0'),
|
String(now.getSeconds()).padStart(2, '0')
|
].join('');
|
|
// 拆分原始文件名和后缀
|
const lastDotIndex = originalFileName.lastIndexOf('.');
|
const baseName = lastDotIndex === -1
|
? originalFileName
|
: originalFileName.slice(0, lastDotIndex);
|
const extension = lastDotIndex === -1
|
? ''
|
: originalFileName.slice(lastDotIndex + 1);
|
|
// 生成新文件名(基础名_时间戳.后缀)
|
this.fileName = `${baseName}_${timestamp}.${extension}`;
|
console.log('新文件名:', this.fileName);
|
}
|
},
|
|
methods: {
|
openExcel() {
|
const fileUrl = this.imageUrl;
|
uni.downloadFile({
|
url: fileUrl,
|
success: (res) => {
|
console.log(res);
|
|
let fileName = this.fileName;
|
let fileExt = fileName.split('.').pop();
|
// let newFilePath = "_doc/uniapp_temp_1742877118745/download" + "/" + fileName;
|
// console.log('newFilePath', newFilePath)
|
if (fileExt === 'xls' || fileExt === 'xlsx' || fileExt === 'pdf'|| fileExt === 'jpg'|| fileExt === 'png') {
|
plus.io.resolveLocalFileSystemURL(res.tempFilePath, (entry) => {
|
// 获取文件所在的目录
|
entry.getParent((parentEntry) => {
|
let newFileName = this.fileName; // 新的文件名
|
|
// 移动并重命名文件
|
entry.moveTo(
|
parentEntry,
|
newFileName,
|
(newEntry) => {
|
console.log('重命名成功:', newEntry.fullPath);
|
|
// 打开 Excel 文件
|
plus.runtime.openFile(newEntry.fullPath, {}, (e) => {
|
console.error('无法打开 Excel 文件:', e);
|
});
|
|
let pages = getCurrentPages();
|
let beforePage = pages[pages.length - 2];
|
uni.navigateBack({
|
delta: 1, //返回的页面数,如果为1表示返回上一页
|
success: (event) => {
|
beforePage.$vm.reload()
|
}
|
});
|
|
},
|
(err) => {
|
console.error('重命名失败:', err);
|
}
|
);
|
}, (err) => {
|
console.error('获取父目录失败:', err);
|
});
|
}, (err) => {
|
console.error('获取文件失败:', err);
|
});
|
} else {
|
console.error('文件格式不匹配:', fileExt);
|
uni.showToast({
|
title: '文件格式不支持',
|
icon: 'none'
|
});
|
}
|
}
|
})
|
}
|
}
|
};
|
</script>
|
|
<style scoped>
|
button {
|
padding: 10px 20px;
|
background-color: #007aff;
|
color: white;
|
border: none;
|
border-radius: 5px;
|
font-size: 16px;
|
}
|
</style>
|