uniapp开发小程序,导出文件打开并保存,实现过程downloadFile下载,openDocument打开_uni.downloadfile
uniapp开发小程序,导出文件打开并保存
实现思路
1、调用请求获取到后端接口返回的下载文件的url路径 (注意必须是https的路径,域名需要配置在微信小程序后台的合法域名里面)
2、使用 uni.downloadFile 方法 (下载文件资源到本地,客户端直接发起一个 HTTP GET 请求,返回文件的本地临时路径。)
3、使用 uni.openDocument(OBJECT)方法
新开页面打开文档,支持格式:doc, xls, ppt, pdf, docx, xlsx, pptx。
建议给用户添加一句提示,下载下来的文件会自动打开
// html导出
submitExport(){uni.showModal({content:\"导出的Excel文件将自动打开,请点击右上角\"更多\"选择保存\",title:\"温馨提示\",success(res) {if(res.confirm){this.export()}}})},export(){// 请求用自己项目的封装请求,我这用了我自己项目的this.$http.mallbusiness({url: \"写自己后端给的接口\",data: this.queryString,type: \"queryString\",}).then(res => {if (res.code == 200) {uni.downloadFile({url: res.data,success: (downloadRes) => {console.log(downloadRes,\"downloadRes\")if (downloadRes.statusCode === 200) {// 文件临时路径const tempFilePath = downloadRes.tempFilePath;//打开文件uni.openDocument({filePath: tempFilePath,showMenu: true,success: () => {this.$u.toast(\"导出成功!\");this.exportClose()},fail: (err) => {console.error(\'打开文件失败\', err);this.$u.toast(\"文件已下载,但无法打开\");}});} else {this.$u.toast(\"下载失败,请重试\");}},fail: (err) => {console.error(\'下载文件失败\', err);this.$u.toast(\"下载失败,请重试\");},complete: () => {uni.hideLoading();}});} else {this.$u.toast(res.message)}})},