【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",
	})
	}
});

}
相关推荐
jingling5551 小时前
【Vue3 实战】插槽封装与懒加载
前端·javascript·vue.js
??? Meggie1 小时前
【Python】保持Selenium稳定爬取的方法(防检测策略)
开发语言·python·selenium
酷爱码3 小时前
如何通过python连接hive,并对里面的表进行增删改查操作
开发语言·hive·python
画个大饼3 小时前
Go语言实战:快速搭建完整的用户认证系统
开发语言·后端·golang
喵先生!4 小时前
C++中的vector和list的区别与适用场景
开发语言·c++
Thomas_YXQ4 小时前
Unity3D Lua集成技术指南
java·开发语言·驱动开发·junit·全文检索·lua·unity3d
xMathematics5 小时前
计算机图形学实践:结合Qt和OpenGL实现绘制彩色三角形
开发语言·c++·qt·计算机图形学·cmake·opengl
Freedom风间6 小时前
前端优秀编码技巧
前端·javascript·代码规范
萌萌哒草头将军6 小时前
🚀🚀🚀 Openapi:全栈开发神器,0代码写后端!
前端·javascript·next.js
萌萌哒草头将军6 小时前
🚀🚀🚀 Prisma 爱之初体验:一款非常棒的 ORM 工具库
前端·javascript·orm