最近写的uniapp项目需要新增一个pdf下载和打开查看功能,摸索了半天终于写了出来,现分享出来供有需要的同行参考,欢迎指正
async function DownloadSignature() {//请求后端接口,返回值为一个url地址let res=await req.flow.flowDownload(data.flowId)uni.downloadFile({//res.data就是返回的地址url: res.data,success: function (res) {if (res.statusCode === 200) {// 下载成功const filePath = res.tempFilePath; // 下载后的临时文件路径uni.saveFile({tempFilePath: filePath,success: function (listRes) {//此API是为了拿到文件保存的详细路径plus.io.requestFileSystem( plus.io.PRIVATE_DOC, function( fs ) { // 拿到 _doc 所在的完整路径 console.log(fs.root.fullPath); //弹出文件保存路径http.hint('文件保存成功'+fs.root.fullPath+listRes.savedFilePath,3000)}, function ( e ) { console.log( "Request file system failed: " + e.message ); } );//保存成功后,调用文件打开方法uni.openDocument({filePath,success: function(file) {console.log('file-success',file);}});},fail: function (err) {// 保存文件失败uni.showToast({title: '保存文件失败',icon: 'none'});}});} else {// 下载失败uni.showToast({title: '下载失败',icon: 'none'});}},fail: function (err) {// 下载请求失败uni.showToast({title: '下载请求失败',icon: 'none'});}});}
因为功能写的紧急,还没有摸索出文件重命名方法(因为下载后的文件名是时间戳,这属于优化的一部分)以及自定义文件保存路径方法,