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