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

}
相关推荐
lly2024068 小时前
Bootstrap 警告框
开发语言
2601_949146539 小时前
C语言语音通知接口接入教程:如何使用C语言直接调用语音预警API
c语言·开发语言
曹牧9 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
KYGALYX9 小时前
服务异步通信
开发语言·后端·微服务·ruby
zmzb01039 小时前
C++课后习题训练记录Day98
开发语言·c++
猫头虎10 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
Moment10 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
YUJIANYUE10 小时前
PHP纹路验证码
开发语言·php
爱敲代码的小鱼10 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax
万物得其道者成10 小时前
UniApp 多端滑块验证码插件 zxj-slide-verify 实用指南
uni-app