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

}
相关推荐
维吉斯蔡6 小时前
【VS Code / Cursor】文件夹右键快捷打开与文件类型自动关联
开发语言·程序人生·学习方法
猫猫不是喵喵.7 小时前
Vue3 Props 属性
前端·javascript·vue.js
luj_17688 小时前
星火科技助力边远地区防病攻坚
c语言·开发语言·c++·经验分享·算法
always_TT8 小时前
【Python 日志记录:logging 模块入门】
开发语言·python·php
xcLeigh9 小时前
Go入门:变量声明的五种方式详解
java·开发语言·golang
zmzb01039 小时前
C++课后习题训练记录Day175
开发语言·c++
脱胎换骨-军哥10 小时前
C++ 代码规范与格式化指南
开发语言·c++·代码规范
枕星而眠10 小时前
C++ STL Map容器完全指南:从有序红黑树到无序哈希表
java·开发语言
爱吃牛肉的大老虎11 小时前
Rust对象之结构体,枚举,特性
开发语言·后端·rust
bbq粉刷匠12 小时前
HashMap 底层原理深度拆解(二):putVal 完整链路解析(懒加载 · 链表遍历 · 尾插法)
java·开发语言·哈希算法