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

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

相关推荐
不法1 小时前
uniapp 百家云直播插件打包失败
uni-app·插件使用
换日线°4 小时前
微信小程序单双周选择排序有效果图
微信小程序
moxiaoran57538 小时前
uni-app学习笔记五-vue3响应式基础
笔记·学习·uni-app
新老农10 小时前
php数据导出pdf,然后pdf转图片,再推送钉钉群
pdf·php·钉钉
小新11010 小时前
微信小程序学习之底部导航栏
微信小程序·导航栏
小新11011 小时前
微信小程序 密码框改为text后不可见,需要点击一下
微信小程序·小程序·notepad++
Maitians11 小时前
微信小程序 自定义图片分享-绘制数据图片以及信息文字
微信小程序·小程序
琉璃℡初雪12 小时前
vue2/3 中使用 @vue-office/docx 在网页中预览(docx、excel、pdf)文件
vue.js·pdf·excel
一个懒鬼16 小时前
Edge浏览器打开PDF文件显示空白(每次需要等上一会)
windows·pdf