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

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()) {
										
										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{
								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)
						}
					}
				}
			}

调用方法

this.PickFile((e) => {
  //文件回调
						console.log(e, '=================')
						//文件类型
					}, 'application/*|text/*')

调用前检测存储权限是否开启

plus.android.requestPermissions(['android.permission.READ_EXTERNAL_STORAGE'],
						(e) => {
							console.log(e)
							if (e.deniedAlways.length > 0) { //权限被永久拒绝  
								uni.showModal({
									title: '提示',
									content: '请打开设备存储权限',
									// showCancel: false, // 不显示取消按钮
									success(res) {
										if (res.confirm) {
											let Intent = plus.android.importClass(
												"android.content.Intent");
											let Settings = plus.android.importClass(
												"android.provider.Settings");
											let Uri = plus.android.importClass("android.net.Uri");
											let mainActivity = plus.android.runtimeMainActivity();
											var intent = new Intent();
											intent.setAction(Settings
												.ACTION_APPLICATION_DETAILS_SETTINGS);
											let uri = Uri.fromParts("package", mainActivity
												.getPackageName(),
												null);
											intent.setData(uri);
											mainActivity.startActivity(intent);
										}
									}
								}); // 弹出提示框解释为何需要权限,引导用户打开设置页面开启  
							} else {
							}
						})
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

狗_都不做前端

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值