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

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

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

步骤1:下载文件

	    uni.downloadFile({
				url:url, //调接口返给的url
				success: function (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: function(res) {
						uni.showToast({
							icon: 'none',
							mask: true,
							title: '文件已保存:' + res.savedFilePath, //保存路径
							duration: 3000,
						});
						setTimeout(() => {
							//打开文档查看
							uni.openDocument({
								filePath: res.savedFilePath,
								success: function(res) {
									// console.log('打开文档成功');
								}
							});
						}, 3000)
					}
				});
			}

步骤三:打开文档查看

	//打开文档查看
uni.openDocument({
		filePath: res.savedFilePath,
		success: function(res) {
									// console.log('打开文档成功');
		}
});

2.H5实现下载资源功能

步骤1:获取下载文件

    uni.downloadFile({
				url:url, //调接口返给的url
				success: function (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(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
				  console.log(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浏览文件直接后台给文件地址即可 

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dogface07

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值