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

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

相关推荐
2023框框4 小时前
给PDF书籍添加书签
pdf
月屯7 小时前
Pandoc 之--pdf-engine
java·开发语言·pdf
开开心心_Every13 小时前
Word转PDF工具,免费生成图片型文档
网络·笔记·pdf·word·powerpoint·excel·azure
homelook14 小时前
uniapp蓝牙demo
uni-app
一个无名的炼丹师14 小时前
[硬核实战] 解锁多模态RAG:构建能“看懂”PDF复杂图表的智能问答系统
人工智能·python·pdf·多模态·rag
2501_915909061 天前
手机崩溃日志导出的工程化体系,从系统级诊断到应用行为分析的多工具协同方法
android·ios·智能手机·小程序·uni-app·iphone·webview
toooooop81 天前
微信小程序轮播图高度自适应优化
微信小程序·小程序
郑州光合科技余经理1 天前
技术视角:海外版一站式同城生活服务平台源码解析
java·开发语言·uni-app·php·排序算法·objective-c·生活
StarChainTech1 天前
电动车租赁行业的核心需求:智能中控设备的选择与技术方案
物联网·微信小程序·小程序·软件需求·共享经济
非凡ghost2 天前
Xournal++(PDF文档注释工具) 中文绿色版
学习·pdf·生活·软件需求