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

}
相关推荐
非 白2 分钟前
【Java分布式】Nacos注册中心
java·开发语言·nacos·注册中心
88号技师2 分钟前
2025年2月最新SCI-鹰鱼优化算法HawkFish Optimization Algorithm-附Matlab免费代码
开发语言·算法·matlab·优化算法
quitv24 分钟前
react脚手架配置别名
前端·javascript·react.js
Joey_friends43 分钟前
【Linux】线程详解
开发语言
_GR1 小时前
Qt开发⑧Qt的窗口_下_浮动窗口+对话框
开发语言·css·c++·qt·microsoft
Good Note1 小时前
Golang——常用库context和runtime
开发语言·爬虫·golang
清河__2 小时前
【Go】十七、grpc 服务的具体功能编写
开发语言·后端·golang
张声录12 小时前
国密算法Sm2工具类--golang实现版
开发语言·后端·golang
HH牛码2 小时前
C# 中 Array、ArrayList 和 List 的比较
开发语言·c#
Gazer_S2 小时前
【现代前端框架中本地图片资源的处理方案】
前端·javascript·chrome·缓存·前端框架