网站开发 法律申明,网站建设及维护服务器,在婚纱店做网站优化,前端培训出来进公司都不会uniapp实现微信小程序下载资源功能和h5有很大的不同#xff0c;后台需返回blob文件流
1.微信小程序实现下载资源功能
步骤1#xff1a;下载文件
uni.downloadFile({url:url,//调接口返回urlsuccess:(res){uni.hideLoading();if(res.statusCode200){var tempFilePath …uniapp实现微信小程序下载资源功能和h5有很大的不同后台需返回blob文件流
1.微信小程序实现下载资源功能
步骤1下载文件
uni.downloadFile({url:url,//调接口返回urlsuccess:(res){uni.hideLoading();if(res.statusCode200){var tempFilePath res.tempFilePath;saveFile(tempFilePath);}else{uni.showToast({icon:none,title:报告下载失败})}},fail:err{uni.hideLoading();uni.showToast({icon:none,title:报告下载失败})reject(err);}
})步骤2保存文件
saveFile(tempFilePath){//保存到本地//文件保存到本地uni.saveFile({tempFilePath:tempFilePath,//临时路径success:res{uni.showToast({icon:none, mask:true,title:文件已保存res.savedFilePath,//保存路径duration:3000})setTimeOut((){//打开文档查看uni.openDocument({filePath:res.savedFilePath,success:res{console.log(打开文档成功);}})},3000)}})
}步骤3打开文档查看
//打开文档查看
uni.openDocument({filePath:res.savedFilePath,success:res{console.log(打开文档成功);}
})2.H5实现下载资源功能
步骤1获取下载文件
uni.downloadFile({url:url,//调接口返回的urlsuccess:res{uni.hideLoading();if(res.statusCode200){var tempFilePath res.tempFilePath;saveFile(tempFilePaht);}else{uni.showToast({icon:none,title:报告下载失败})}},fail:err{uni.hideLoading();uni.showToast({icon:none,title:报告下载失败})reject(err);}
})步骤2保存文件
saveFile(url){//保存到本地try{const fileName 报告名称;//new Blob 实例化文件流//let url fileData//const url window.URL.createObjectURL(new Blob([fileData],{type:application/pdf}))const link document.createElement(a);link.style.display none;link.href url;link.setAttribute(download,fileName);document.body.appendChild(link);link.click();//下载完成移除元素document.body.removeChild(link);//释放掉blob对象window.URL.revokeObjectURL(url)uni.showToast({title:下载成功})}catch(error){uni.showToast({title:下载失败})}
}h5浏览文件直接后台给文件地址即可。
以上内容摘自https://blog.csdn.net/panfu163/article/details/132832484
以上代码并未通过验证后续使用到有问题的话会补充。