uni-app小程序:文件下载打开文件方法苹果安卓都适用

api:

复制代码
const filetype = e.substr(e.lastIndexOf('.')+1)//获取文件地址的类型
console.log('文档',filetype)
uni.downloadFile({
	url: e,//e是图片地址
    success(res) {
	console.log(res)
	if (res.statusCode === 200) {
		console.log('下载成功',);
		var filePath = encodeURI(res.tempFilePath);//这里直接复制不用改值
		uni.openDocument({
		    filePath: encodeURI(filePath),
		    fileType: filetype,//这样文件地址是什么类型,api打开的就是什么类型了,前提是uni.openDocument支持的类型
			showMenu: true,
			success: function(res) {
				console.log('打开文档成功');
				  },
				fail(e) {
					console.log('打开失败',e)
						}
						   });
						} else {
						    console.log('下载失败');
					    }
					}
				});

encodeURI的作用:

encodeURI函数将URI中的特殊字符转换为它们的UTF-8编码表示形式,以确保它们在传输和处理过程中不会被误解或错误解析。这样可以避免因特殊字符导致的错误或安全问题。

源码:

运行效果:

点击文件1就可以下载打开文件预览了

相关推荐
ue星空1 小时前
第一个安卓程序
android
淡淡的香烟1 小时前
Androidiot蓝牙配网简单封装
android·物联网
gxgldyh1 小时前
Android Framework源码解析(九):App进程诞生全流程——从AMS请求到Zygote fork源码深度拆解
android·framework·zygote·android 启动流程·android app创建流程
牛哇网络工作室8 小时前
UnityHDRP写实数字人全流程基础5—语音输入和语音识别
android·unity·c#·游戏引擎·aigc·语音识别·xcode
一笑的小酒馆9 小时前
Androidiot蓝牙配网简单封装
android
愚公搬代码12 小时前
【愚公系列】《Android应用案例开发大全》016-LBS类应用掌上杭州(辅助工具类的开发)
android·前端
g105655913912 小时前
LAMP博客平台Wordpress实战
android·mysql·nginx·php
hunterandroid13 小时前
[Android 从零到一] Compose LazyColumn 性能优化:key、稳定性与重组治理
android·前端
pengyu14 小时前
【Kotlin 协程修仙录 · 元婴境 · 中阶】 | 操作符真解:Flow 中间操作符与数据流变幻术
android·kotlin
pengyu15 小时前
【Kotlin 协程修仙录 · 元婴境 · 初阶】 | 冷流初啼:Flow 的基础与响应式编程的入门
android·kotlin