【uniapp 解决h5 uni.saveFile 不生效】2种方法解决

用uni.saveFile h5报错 saveFile API saveFile is not yet implemented

查看文档发现不支持h5

解决方法:

这个我用了pc 端一样的方法用a标签来下载保存代码如下:

第一种:

java 复制代码
 const a = document.createElement('a');
 a.href = filePath; //filePath 这里的地址是 uni.downloadFile 中的返回值里的地址
a.download = finName; // 可以设置下载文件名,如果是空字符串,则使用服务器端设置的文件名
a.click();

第二种 可以引用js第三方库来进行保存

先安装 file-saver

bash 复制代码
npm install file-saver --save

引用

javascript 复制代码
	import { saveAs } from 'file-saver';
	 //filePath 这里的地址是 uni.downloadFile 中的返回值里的地址
	 //finName 下载文件名
	saveAs(filePath,finName)

整体代码:

javascript 复制代码
fileDwonload(url='https://example.com/somefile.pdf') {

	uni.showLoading({title: '下载中'});
	const index = url.lastIndexOf('/');
	const finName = url.slice(index + 1, url.length)//下载文件
	uni.downloadFile({ 
	    url: url, //请求地址
		savePath: finName,
		success: (res) => {
		//下载成功
		 if (res.statusCode === 200) {
			//保存文件
           let filePath = res.tempFilePath;
			// #ifdef H5 
			// saveAs(filePath,finName);
			 const a = document.createElement('a');
			 a.href = filePath;
			 a.download = finName; // 可以设置下载文件名,如果是空字符串,则使用服务器端设置的文件名
			 a.click();
			// #endif
			//  #ifdef MP-WEIXIN || APP-PLUS 	
			uni.saveFile({
			tempFilePath: filePath,
			success: function(filRes) {
				console.log(filRes, '=====>');
			},
			fail: function(err) {
					console.log('保存失败');
				}
		})
		// #endif			
		uni.hideLoading()
	}
},
fail: (e) => {
  console.log(e, '文件下载失败')
	uni.showToast({
			title: '文件下载失败',
			icon: "error",
	})
	}
});

}
相关推荐
刘发财11 小时前
弃用html2pdf.js,这个html转pdf方案能力是它的几十倍
前端·javascript·github
ssshooter18 小时前
看完就懂 useSyncExternalStore
前端·javascript·react.js
Live0000019 小时前
在鸿蒙中使用 Repeat 渲染嵌套列表,修改内层列表的一个元素,页面不会更新
前端·javascript·react native
柳杉19 小时前
使用Ai从零开发智慧水利态势感知大屏(开源)
前端·javascript·数据可视化
球球pick小樱花20 小时前
游戏官网前端工具库:海内外案例解析
前端·javascript·css
喝水的长颈鹿20 小时前
【大白话前端 02】网页从解析到绘制的全流程
前端·javascript
用户145369814587820 小时前
VersionCheck.js - 让前端版本更新变得简单优雅
前端·javascript
codingWhat20 小时前
整理「祖传」代码,就是在开发脚手架?
前端·javascript·node.js
码路飞20 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
Lee川20 小时前
优雅进化的JavaScript:从ES6+新特性看现代前端开发范式
javascript·面试