Uniapp App(Android)端 非媒体文件的选择、上传、下载、查看功能

Uniapp App(Android)端 非媒体文件的选择是其中的难点,官方 uni-file-picker 但是这个组件App端只支持上传图片和视频,而官方文档提供的uni.chooseFile(),也不支持App端。安卓端选取非图片文件(plus.io.chooseFile)时文件地址是content://开头的url。content://开头的URI是一种内容URI,它不直接暴露文件的物理路径(如/storage/emulated/0/...),而是通过Android的<ml-search-more text="ContentResolver" _type="textDirective">ContentResolver</ml-search-more>机制进行间接访问。这种设计源于Android的存储访问框架(SAF),当应用请求访问外部存储文件时,系统会授予临时权限,返回content://形式的URI以确保安全性,防止应用直接读取或写入其他应用的文件。接下来使用plus.io.chooseFile 进行文件选取并处理成能使用的本地路径,代码如下:

javascript 复制代码
onAndriodChooseFile() {
			const MediaStore = plus.android.importClass('android.provider.MediaStore');
			const main = plus.android.runtimeMainActivity();

			plus.io.chooseFile({
				title: '选择文件',
				filter: '.xlsx,.docx', // 允许的文件类型  
				multiple: false, // 是否允许多选  
			}, (e) => {
				// 获取文件的虚拟路径
				const contentUri = decodeURIComponent(e.files[0])
				const uri = MediaStore.Files.getContentUri("external");
				// 给系统导入 contentResolver
				plus.android.importClass(main.getContentResolver());
				const arr = contentUri.split(':')
				// 通过查询的方式用虚拟路径的id1获取到文件的真实路径
				let cursor = main.getContentResolver().query(uri, ['_data'], "_id=?", [arr[arr.length - 1]], null);
				plus.android.importClass(cursor);
				let result
				if (cursor != null && cursor.moveToFirst()) {
					let column_index = cursor.getColumnIndexOrThrow('_data');
					result = cursor.getString(column_index)   // result即文件的真实路径
					cursor.close();
				}
				result = 'file:/' + result  // 此处拿到本地路径,后续根据你的业务代码进行处理即可
			    console.log('result:', result)
			})
		}

2、上传文件使用官方的方法: 参考uni.uploadFile

3、网络文件需要通过官方的方法下载到本地才能预览: 参考uni.downloadFile (本地文件忽略这一步)

4、打开文档也是使用官方的方法,参考:uni.openDocument

相关推荐
2501_916007471 天前
Bundle ID 注册与管理 App ID 创建指南 命名规则 权限开关与删除注意事项
android·ios·小程序·https·uni-app·iphone·webview
PedroQue991 天前
uni-app路由插件化:解锁高效开发新姿势
前端·uni-app
2501_915909061 天前
iOS 证书创建与管理 类型限制 p12 密码与云备份实操
android·ios·小程序·https·uni-app·iphone·webview
anyup1 天前
【2026年8月】uView Pro 千星,还拿到了 GVP
前端·uni-app·github
andr_gale2 天前
02_uniapp自定义上凸效果的底部TabBar
前端·javascript·uni-app·移动端
不爱说话郭德纲2 天前
uni-app x iOS 扫码模糊怎么办?AVFoundation 灰尘级别摄像头助你超广角聚焦
前端·uni-app·app
CHB3 天前
uni-app x 蒸汽模式 性能测试基准报告 Benchmark【Android版】
android·ios·uni-app
游戏开发爱好者85 天前
系统状态:专为iPhone和iPad设计的实时系统性能监控工具全面介绍
android·ios·小程序·uni-app·iphone·webview·ipad
2501_915909065 天前
全面解析iOS应用上架到App Store的完整流程与关键注意事项
android·macos·ios·小程序·uni-app·cocoa·iphone
2501_915106325 天前
iOS 证书类型及作用说明 账号证书与签名配置的完整解读
android·ios·小程序·https·uni-app·iphone·webview