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

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

相关推荐
dcloud_jibinbin1 天前
【uniapp】体验优化:开源工具集 uni-toolkit 发布
前端·webpack·性能优化·小程序·uni-app·vue
前端小菜袅1 天前
uniapp配置自动导入uni生命周期等方法
前端·javascript·uni-app
焚 城1 天前
UniApp中Flex布局学习
学习·uni-app
你真的可爱呀1 天前
uniapp学习【整体实践】
前端·学习·uni-app·实践
用力的活着1 天前
uniapp 微信小程序蓝牙接收中文乱码
微信小程序·小程序·uni-app
知识分享小能手1 天前
微信小程序入门学习教程,从入门到精通,电影之家小程序项目知识点详解 (17)
前端·javascript·学习·微信小程序·小程序·前端框架·vue
南风微微吹1 天前
【四级】全国大学英语四级历年真题及答案解析PDF电子版(2015-2025年6月)
pdf·英语四级
starxg1 天前
bkhtmltopdf - 高性能 HTML 转 PDF 工具(代替 wkhtmltopdf)
java·pdf·html·wkhtmltopdf·htmltopdf
SoberChina1 天前
Jasperreport 导出word 多个element重叠部分导致不显示(不支持)
pdf·word·jaspersoft·模版打印