uniapp 安卓 plus调用原生文件选择

typescript 复制代码
async PickFile(callback, acceptType) {
				try {
					await this.getPermissions()
					var CODE_REQUEST = 1000;
					var main = plus.android.runtimeMainActivity();
					if (plus.os.name == 'Android' && typeof callback == 'function') {
						var Intent = plus.android.importClass('android.content.Intent');
						var intent = new Intent(Intent.ACTION_GET_CONTENT);
						intent.addCategory(Intent.CATEGORY_OPENABLE);
						if (acceptType) {
							intent.setType(acceptType);
						} else {
							intent.setType("*/*");
						}
						main.onActivityResult = function(requestCode, resultCode, data) {
							if (requestCode == CODE_REQUEST) {
								var uri = data.getData();
								plus.android.importClass(uri);
								var Build = plus.android.importClass('android.os.Build');
								var isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

								var DocumentsContract = plus.android.importClass(
									'android.provider.DocumentsContract');
								// DocumentProvider
								if (isKitKat && DocumentsContract.isDocumentUri(main, uri)) {
									console.log("版本大于 4.4 ", uri.getAuthority());
									// ExternalStorageProvider
									if ("com.android.externalstorage.documents" == uri.getAuthority()) {
										var docId = DocumentsContract.getDocumentId(uri);
										var split = docId.split(":");
										var type = split[0];
										console.log(type)
										if ("primary" == type) {
											var Environment = plus.android.importClass('android.os.Environment');
											callback(Environment.getExternalStorageDirectory() + "/" + split[1]);
										} else {
											var System = plus.android.importClass('java.lang.System');
											var sdPath = System.getenv("SECONDARY_STORAGE");
											if (sdPath) {
												callback(sdPath + "/" + split[1]);
											}
										}
									}
									// DownloadsProvider
									else if ("com.android.providers.downloads.documents" == uri.getAuthority()) {
										// uni.showToast({
										// 	title: '当前模块文件不可用!请切换为其他模块选择文件',
										// 	icon: 'none'
										// })
										// return false
										// 文件选择是下载内容 非根目录时 导致文件路径出问题 目前没有解决办法禁用次模块
										
										var id = DocumentsContract.getDocumentId(uri);
										var ContentUris = plus.android.importClass('android.content.ContentUris');
										console.log(id, '+++++++++++++++++++++', uri.getScheme())
										if (id.indexOf('msf:') > -1) {
											id = id.split(":")[1]
										}
										console.log(id, '+++++++++++++++++++++')
										let Uri = plus.android.importClass('android.net.Uri')
										// console.log(Uri.parse("content://downloads/public_downloads"))
										var contentUri = ContentUris.withAppendedId(
											// Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
											Uri.parse("content://downloads/public_downloads"), id);
										console.log(contentUri)

										if (contentUri) {
											let path = getDataColumn(main, contentUri, null, null)
											callback(path);
											return false
										}
										contentUri = ContentUris.withAppendedId(
											// Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
											Uri.parse("content://downloads/my_downloads"), id);
										console.log(contentUri)

										if (contentUri) {
											let path = getDataColumn(main, contentUri, null, null)
											callback(path);
											return false
										}
										let fileName = getFileName(main, uri)
										console.log(fileName,'--------------------')
										callback(getFileExplorer('/storage/emulated/0/Download',fileName+''))
										return "fileName = " + fileName;
									}
									// MediaProvider
									else if ("com.android.providers.media.documents" == uri.getAuthority()) {
										console.log(uri)
										var docId = DocumentsContract.getDocumentId(uri);
										var split = docId.split(":");
										var type = split[0];
										console.log(type)
										var MediaStore = plus.android.importClass('android.provider.MediaStore');
										let contentUri = ""
										if ("image" == type) {
											contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
										} else if ("video" == type) {
											contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
										} else if ("audio" == type) {
											contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
										} else {
											contentUri = MediaStore.Files.getContentUri("external")
										}
										var selection = "_id=?";
										var selectionArgs = new Array();
										selectionArgs[0] = split[1];
										callback(getDataColumn(main, contentUri, selection, selectionArgs));
									}
								}
								// MediaStore (and general)
								else if ("content" == uri.getScheme()) {
									callback(getDataColumn(main, uri, null, null));
								}
								// File
								else if ("file" == uri.getScheme()) {
									callback(uri.getPath());
								}
							}
						}
						main.startActivityForResult(intent, CODE_REQUEST);
					}
				} catch (e) {
					console.log(e)
				}


				function getFileExplorer(path, fileName) {
					try {
						let File = plus.android.importClass("java.io.File")
						let directory = new File(path);
						let files = directory.listFiles()
						let nowPath = ''
						for(let i =0;i<files.length;i++){
							
							if (files[i].isDirectory()) {
								nowPath = getFileExplorer(files[i].getAbsolutePath(),fileName)
							}else{
								console.log(files[i].getAbsolutePath(),'/storage/emulated/0/Download/WeiXin/最高额信用借款合同补充协议.pdf'.indexOf(fileName),typeof fileName)
								if(files[i].getAbsolutePath().indexOf(fileName) > -1) nowPath = files[i].getAbsolutePath()
							}
							if(nowPath){
								break
							}
						}
						return nowPath
					} catch (e) {
						//TODO handle the exception
						console.log(e)
					}
				}

				function getDataColumn(main, uri, selection, selectionArgs) {
					plus.android.importClass(main.getContentResolver());
					let cursor = main.getContentResolver().query(uri, ['_data'], selection, selectionArgs,
						null);
					console.log(cursor)
					plus.android.importClass(cursor);
					if (cursor != null && cursor.moveToFirst()) {
						var column_index = cursor.getColumnIndexOrThrow('_data');
						var result = cursor.getString(column_index)
						cursor.close();
						return result;
					}
					return null;
				}

				function getFileName(context, uri) {
					console.log('', context.getContentResolver())
					plus.android.importClass(context.getContentResolver());
					try {
						let mimeType = context.getContentResolver().getType(uri);
						console.log(mimeType)
						let filename = null;

						if (mimeType == null && context != null) {
							/* String path = getPath(context, uri);
							 if (path == null) {
							     filename = getName(uri.toString());
							 } else {
							     File file = new File(path);
							     filename = file.getName();
							 }*/
						} else {
							let returnCursor = context.getContentResolver().query(uri, null,
								null, null, null);
							console.log(returnCursor)
							if (returnCursor != null) {
								plus.android.importClass(returnCursor)
								let OpenableColumns = plus.android.importClass('android.provider.OpenableColumns')
								let nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);

								console.log("FUCKFUCK nameIndex", "" + nameIndex);
								returnCursor.moveToFirst();
								console.log(returnCursor.getString(2))
								filename = returnCursor.getString(nameIndex);
								returnCursor.close();
							}
						}
						return filename;
					} catch (e) {
						console.log(e)
					}

				}

				function getDocumentCacheDir(context) {
					try {
						let File = plus.android.importClass('java.io.File')
						let dir = new File('/storage/emulated/0/Download/', 'documents');
						if (!dir.exists()) {
							dir.mkdirs();
						}
						return dir;
					} catch (e) {
						console.log(e)
					}

				}

				function generateFileName(name, directory) {
					if (name == null) {
						return null;
					}
					let File = plus.android.importClass('java.io.File')
					let file = new File(directory, name);

					if (file.exists()) {
						let fileName = name;
						let extension = "";
						let dotIndex = name.lastIndexOf('.');
						if (dotIndex > 0) {
							fileName = name.substring(0, dotIndex);
							extension = name.substring(dotIndex);
						}

						let index = 0;

						while (file.exists()) {
							index++;
							name = fileName + '(' + index + ')' + extension;
							file = new File(directory, name);
						}
					}

					try {
						if (!file.createNewFile()) {
							return null;
						}
					} catch (e) {
						console.log(e)
						return null;
					}

					return file;
				}

				function saveFileFromUri(context, uri, destinationPath) {
					plus.android.importClass('java.io.InputStream');
					let is = null;
					let bos = null;
					let bis = null;
					let FileOutputStream = plus.android.importClass('java.io.FileOutputStream')
					let BufferedOutputStream = plus.android.importClass('java.io.BufferedOutputStream')
					let BufferedInputStream = plus.android.importClass('java.io.BufferedInputStream')
					let FileInputStream = plus.android.importClass('java.io.FileInputStream')
					try {
						plus.android.importClass(context.getContentResolver());

						is = context.getContentResolver().openInputStream(uri)
						bos = new BufferedOutputStream(new FileOutputStream(destinationPath));
						let buffer = new Int8Array(1024);
						bos.write(is.read(buffer));
					} catch (e) {
						console.log(e)
					} finally {
						try {
							if (is != null) is.close();
							if (bos != null) bos.close();
						} catch (e) {
							console.log(e)
						}
					}
				}
			}

调用方法

typescript 复制代码
this.PickFile((e) => {
  //文件回调
						console.log(e, '=================')
						//文件类型
					}, 'application/*|text/*')
相关推荐
拭心11 小时前
Google 提供的 Android 端上大模型组件:MediaPipe LLM 介绍
android
带电的小王13 小时前
WhisperKit: Android 端测试 Whisper -- Android手机(Qualcomm GPU)部署音频大模型
android·智能手机·whisper·qualcomm
梦想平凡13 小时前
PHP 微信棋牌开发全解析:高级教程
android·数据库·oracle
元争栈道14 小时前
webview和H5来实现的android短视频(短剧)音视频播放依赖控件
android·音视频
web1508509664114 小时前
在uniapp Vue3版本中如何解决webH5网页浏览器跨域的问题
前端·uni-app
阿甘知识库15 小时前
宝塔面板跨服务器数据同步教程:双机备份零停机
android·运维·服务器·备份·同步·宝塔面板·建站
元争栈道15 小时前
webview+H5来实现的android短视频(短剧)音视频播放依赖控件资源
android·音视频
MuYe15 小时前
Android Hook - 动态加载so库
android
居居飒16 小时前
Android学习(四)-Kotlin编程语言-for循环
android·学习·kotlin
Henry_He19 小时前
桌面列表小部件不能点击的问题分析
android