业务需求是移动端提交各种申请时,需要下载提供的指定的模板进行,在进行提交。 但是当打包成app后,执行uni.downloadFile下载不是很好找到对应的下载文件,根据网上的说法,进行了另一种下载。
这是之前的写法:
// #ifdef APP-PLUS
var that = this;
uni.downloadFile({
url: `${
locals}/Template/${
that.templateFile}`,
header: {
token: uni.getStorageSync('token')
},
success: data => {
uni.saveFile({
//文件保存到本地
tempFilePath: data.tempFilePath, //临时路径
success: function(res) {
that.$refs.uToast.show({
...that.$GetMssage(true, '文件已保存')
});
setTimeout(() => {
uni.openDocument({
filePath: res.savedFilePath,
success: function(res) {
console.log('打开文档成功');
}
});
}, 2000);
}
});
}
});
// #endif
这是经过查询资料后,新的写法,亲测有效。
// #ifdef APP-PLUS
var that = this;
var url = `${
locals}/Template/${
that.templateFile}`;
let dtask = plus.downloader.createDownload(
url,
{
//本地路径开头使用file://,跟上手机文件本地目录storage/emulated/0,就是用户文件管理器能看到的了,之后我创建微垠作为文件夹,后缀是用于文件命名和格式修改,大家可以使用变量。
// ***这块算是自己新建一个文件夹的名字,后面跟的文件名字
filename: 'file://storage/emulated/0/***/' + that.templateFile //利用保存路径,实现下载文件的重命名
},
function(d, status) {
//d为下载的文件对象
if (status == 200) {
//下载成功,d.filename是文件在保存在本地的相对路径,使用下面的API可转为平台绝对路径
// let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);
// plus.runtime.openFile(d.filename); //选择软件打开文件
// 上面这个打开文件,好像是因为本地没有下载对应wps等软件,所以这点修改成一个提示,而非自动打开了。
that.$refs.uToast.show({
...that.$GetMssage(true, '模板下载成功')
});
} else {
//下载失败
plus.downloader.clear(); //清除下载任务
}
}
);
dtask.start();
// #endif