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_9151063236 分钟前
app 上架过程,安装包准备、证书与描述文件管理、安装测试、上传
android·ios·小程序·https·uni-app·iphone·webview
2501_915106321 小时前
使用 Sniffmaster TCP 抓包和 Wireshark 网络分析
网络协议·tcp/ip·ios·小程序·uni-app·wireshark·iphone
宠友信息2 小时前
2025社交+IM及时通讯社区APP仿小红书小程序
java·spring boot·小程序·uni-app·web app
“负拾捌”3 小时前
python + uniapp 结合腾讯云实现实时语音识别功能(WebSocket)
python·websocket·微信小程序·uni-app·大模型·腾讯云·语音识别
局外人LZ1 天前
Uniapp脚手架项目搭建,uniapp+vue3+uView pro+vite+pinia+sass
前端·uni-app·sass
2501_915918411 天前
在 iOS 环境下查看 App 详细信息与文件目录
android·ios·小程序·https·uni-app·iphone·webview
前端呆头鹅1 天前
Websocket使用方案详解(uniapp版)
websocket·网络协议·uni-app
浮桥1 天前
uniapp+h5 公众号实现分享海报绘制
uni-app·notepad++
2501_916007471 天前
没有 Mac 用户如何上架 App Store,IPA生成、证书与描述文件管理、跨平台上传
android·macos·ios·小程序·uni-app·iphone·webview
wangjun51591 天前
uniapp uni.downloadFile 偶发性下载文件失败 无响应
uni-app