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

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

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

步骤1:下载文件

js 复制代码
uni.downloadFile({
	url:url,//调接口返回url
	success:(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:保存文件

js 复制代码
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:打开文档查看

js 复制代码
//打开文档查看
uni.openDocument({
	filePath:res.savedFilePath,
	success:res=>{
		console.log('打开文档成功');
	}
})

2.H5实现下载资源功能

步骤1:获取下载文件

js 复制代码
uni.downloadFile({
	url:url,//调接口返回的url
	success: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:保存文件

js 复制代码
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

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

相关推荐
木易士心21 小时前
一文读懂:微信小程序云数据库直连原理与使用指南
微信小程序·serverless
willow1 天前
uniapp实战
uni-app
只会cv的前端攻城狮1 天前
兼容性地狱-Uniapp钉钉小程序环境隔离踩坑实录
前端·uni-app
明月_清风1 天前
小程序云函数:从入门到全栈的“降维打击”指南
前端·微信小程序·小程序·云开发
拉不动的猪2 天前
移动端调试工具VConsole初始化时的加载阻塞问题
前端·javascript·微信小程序
codingWhat3 天前
小程序里「嵌」H5:一套完整可落地的 WebView 集成方案
前端·uni-app·webview
WangHappy4 天前
不写 Canvas 也能搞定!小程序图片导出的 WebView 通信方案
前端·微信小程序
小时前端4 天前
微信小程序选不了本地文件?用 web-view + H5 一招搞定
前端·微信小程序·uni-app
Mr_li5 天前
给 Vue 开发者的 uni-app 快速指南
vue.js·uni-app
anyup5 天前
🔥2026最推荐的跨平台方案:H5/小程序/App/鸿蒙,一套代码搞定
前端·uni-app·harmonyos