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/*')
相关推荐
瑶琴AI前端1 小时前
uniapp组件实现省市区三级联动选择
java·前端·uni-app
mosen8682 小时前
Uniapp去除顶部导航栏-小程序、H5、APP适用
vue.js·微信小程序·小程序·uni-app·uniapp
Winston Wood2 小时前
Android Parcelable和Serializable的区别与联系
android·序列化
清风徐来辽2 小时前
Android 项目模型配置管理
android
帅得不敢出门2 小时前
Gradle命令编译Android Studio工程项目并签名
android·ide·android studio·gradlew
problc3 小时前
Flutter中文字体设置指南:打造个性化的应用体验
android·javascript·flutter
尚梦9 小时前
uni-app 封装刘海状态栏(适用小程序, h5, 头条小程序)
前端·小程序·uni-app
帅得不敢出门13 小时前
安卓设备adb执行AT指令控制电话卡
android·adb·sim卡·at指令·电话卡
我又来搬代码了15 小时前
【Android】使用productFlavors构建多个变体
android
尚学教辅学习资料16 小时前
基于SSM+uniapp的营养食谱系统+LW参考示例
java·uni-app·ssm·菜谱