小程序: downloadFile + openDocument 下载文件
2个小程序的API,完成下载功能
先看代码
export const promisifyAPIs = (apiNames) => {
const promisifiedAPIs = {};
apiNames.forEach((apiName) => {
if (!wx[apiName]) {
throw new Error(`wx.${apiName} is not a valid function.`);
}
promisifiedAPIs[apiName] = function (options = {}) {
return new Promise((resolve, reject) => {
wx[apiName]({
...options,
success: (res) => resolve(res),
fail: (err) => reject(err)
});
});
};
});
return promisifiedAPIs;
};
const { downloadFile, openDocument } = promisifyAPIs([
'downloadFile',
'openDocument'
]);
核心下载逻辑
const fileUrl = "https://web-assets.alo7.com/assets/pdfs/dummy.pdf";
wx.showLoading({ title: "正在下载文档", mask: true });
try {
const downloadRes = await downloadFile({ url: fileUrl });
const filePath = downloadRes.tempFilePath;
await openDocument({ filePath, showMenu: true });
wx.showToast({
title: "打开文档成功",
icon: "success",
duration: 2000,
});
} catch (e) {
wx.showToast({
title: "打开文档失败",
icon: "none",
duration: 2000,
});
} finally {
wx.hideLoading();
}
配置
- 下载的域名,到
downloadFile
的域名里