当前位置: 首页 > news >正文

uniapp 微信小程序和h5处理文件(pdf)下载+保存到本地+预览功能

uniapp实现微信小程序下载资源功能和h5有很大的不同,后台需返回blob文件流

1.微信小程序实现下载资源功能

步骤1:下载文件

uni.downloadFile({url:url,//调接口返回urlsuccess:(res)=>{uni.hideLoading();if(res.statusCode==200){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.statusCode==200){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

以上代码并未通过验证,后续使用到,有问题的话会补充。

http://www.lryc.cn/news/318615.html

相关文章:

  • Linux从0到1——Linux第一个小程序:进度条
  • 软件工程师,是时候了解下Rust编程语言了
  • SSL---VPN
  • Chrome 跨域问题CORS 分析
  • GPU性能测试中的张量和矩阵运算
  • Linux运维_Bash脚本_编译安装FreeRDP-3.3.0
  • CMake官方教程4--使用表达式生成器
  • git for windows
  • C++实验 面向对象编程
  • VC++ 设置网卡接口MTU大小
  • dpdk-19.11 对向量指令的使用情况分析
  • 使用CIP采集欧姆龙EtherNet/IP从入门到精通
  • 企业如何高效管理微信里的客户?
  • 怎么在windows系统上查看kylinos的md5、sha1、sha256值
  • Windows中在C#中使用Dapper和Mysql.Data库连接MySQL数据库
  • 大一专科,物联网专业,变态成长偏方!
  • MyBatis入门(JDBC规范,MyBatis,连接池,Lombok)【详解】
  • Vue3--数据和方法
  • 网络编程面试题
  • 移动端区分点击和长按
  • 虚拟环境的激活
  • 宏集案例 | 风电滑动轴承齿轮箱内多点温度采集与处理
  • linux 16进制写入
  • 代码随想录算法训练营第60天| Leetcode 84.柱状图中最大的矩形
  • 编写一个简单的cmakelist.txt
  • 基于YOLOv8/YOLOv7/YOLOv6/YOLOv5的零售柜商品检测软件(Python+PySide6界面+训练代码)
  • 数据库的学习
  • matlab去除图片上的噪声
  • C++超详细知识点(五):类的友元函数和友元类
  • SOC设计:关于reset的细节