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

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

相关推荐
UpYoung!12 分钟前
无广技术贴!【PDF编辑器】Solid Converter PDF保姆级图文下载安装指南——实用推荐之PDF编辑软件
学习·数学建模·pdf·编辑器·运维开发·个人开发
Uluoyu26 分钟前
支持Word (doc/docx) 和 PDF 转成一张垂直拼接的长PNG图片工具类
java·pdf·word
2501_916008891 小时前
iOS 26 性能分析深度指南 包含帧率、渲染、资源瓶颈与 KeyMob 协助策略
android·macos·ios·小程序·uni-app·cocoa·iphone
源码_V_saaskw1 小时前
JAVA校园跑腿校园外卖源码校园外卖小程序校园代买帮忙外卖源码社区外卖源码小程序+公众号+h5
java·开发语言·微信小程序·小程序
源码哥_博纳软云1 小时前
JAVA同城预约服务家政服务美容美发洗车保洁搬家维修家装系统源码小程序+公众号+h5
java·开发语言·微信小程序·小程序
iOS阿玮3 小时前
喜欢做马甲包的有福了~现在多了一招续费方式!
uni-app·app·apple
恶猫4 小时前
Polaris Officev9.9.12全功能解锁版
pdf·word·excel·ppt·office·办公·打工
海阔天空66885 小时前
微信小程序添加水印功能
微信小程序·canvas·水印
_AaronWong6 小时前
一键搞定UniApp WiFi连接!这个Vue 3 Hook让你少走弯路
前端·微信小程序·uni-app
SEO-狼术8 小时前
Find Text Fast in Any PDF Document
pdf