可以参考这个 安卓10以上要把文件复制到沙盒目录下来用
function fileSelectStart(options : InfoOptions) {
const context = UTSAndroid.getAppContext();
if (context != null) {
const intent = new Intent(Intent.ACTION_GET_CONTENT);
if (options.scope != null) {
let strPath = options.scope;
strPath = strPath?.replaceAll("/", "%2F");
let uriByScope : Uri = Uri.parse("content://com.android.externalstorage.documents/document/primary%3A" + strPath);
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, uriByScope);
}
intent.setType('*/*');
if (options.mimetype != null) {
switch (options.mimetype) {
case 'image'://图片
intent.setType(IMAGE);
break;
case 'video'://视频
intent.setType(VIDEO);
break;
case 'audio'://音频
intent.setType(AUDIO);
break;
case 'word'://文档
intent.putExtra(Intent.EXTRA_MIME_TYPES, WORD.toTypedArray());
break;
default:
intent.setType(options.mimetype);
break;
}
}
intent.addCategory(Intent.CATEGORY_OPENABLE);
UTSAndroid.getUniActivity()?.startActivityForResult(intent, FILE_SELECT_REQUEST_CODE);
UTSAndroid.onAppActivityResult((requestCode : Int, resultCode : Int, data ?: Intent) => {
UTSAndroid.offAppActivityResult(null);
if (requestCode == FILE_SELECT_REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) {
const fileUri = data.getData();
if (fileUri != null) {
let path = getRealPathFromURI(context, fileUri);
const file = new File(path);
if (file.exists()) {
let upLoadFilePath = file.toString();
let upLoadFileName = file.getName();
let fileSize = file.length();
const extIdx = upLoadFileName.lastIndexOf(".");
let fileExt = extIdx != -1 ? upLoadFileName.substring(extIdx + 1) : "";
const res = {
code: "0",
filePath: upLoadFilePath,
fileName: upLoadFileName,
fileSize: fileSize,
fileExt: fileExt,
errMsg: 'fileselect:ok',
detail: "文件读取成功"
};
options.success?.(res);
options.complete?.(res);
} else {
const res2 = {
code: "1002",
errMsg: 'fileselect:fail',
detail: "文件不存在"
};
options.fail?.(res2);
options.complete?.(res2);
}
}
}
});
} else {
const res3 = {
code: "1005",
errMsg: 'fileselect:fail',
detail: "文件选取出错:context为null"
};
options.fail?.(res3);
options.complete?.(res3);
}
}
function getRealPathFromURI(context : Context, uri : Uri) : string {
const isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
//4.4以下的版本:不支持
//大于4.4
// DocumentProvider
if (isKitKat) {
if (DocumentsContract.isDocumentUri(context, uri)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
if (isExternalStorageDocument(uri)) {
console.log("isExternalStorageDocument");
return saveFileFromUri(context, uri);
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
console.log("isDownloadsDocument");
return saveFileFromUri(context, uri);
}
// MediaProvider
else if (isMediaDocument(uri)) {
console.log("isMediaDocument");
return saveFileFromUri(context, uri);
}
} else {
let docId = DocumentsContract.getDocumentId(uri);
let splits = docId.split(":");
let type = '';
let id = '';
if (splits.length == 2) {
type = splits[0];
id = splits[1];
}
if (isExternalStorageDocument(uri)) {
console.log("isExternalStorageDocument")
if ("primary".equals(type)) {
return Environment.getExternalStorageDirectory().getAbsolutePath() as string + File.separator as string + id;
} else {
return "/storage/" + type + "/" + id;
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
console.log("isDownloadsDocument")
const downloadPath : string = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
const fileName : string = getFileName(context, uri);
return downloadPath + "/" + fileName;
}
// MediaProvider
else if (isMediaDocument(uri)) {
let externalUri : Uri | null = null;
switch (type) {
case "image":
externalUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
break;
case "video":
externalUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
break;
case "audio":
externalUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
break;
case "document":
externalUri = MediaStore.Files.getContentUri("external");
break;
}
if (externalUri != null) {
var selection : string = "_id=?";
let selectionArgs : string[] = [id];
return getDataColumn(context, externalUri, selection, selectionArgs);
}
}
}
}
//其他 content
else if ("content".equals(uri.getScheme())) {
// return getDataColumn(context, uri, null, null);
console.log("content")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
return saveFileFromUri(context, uri);
} else {
return getDataColumn(context, uri, null, null);
}
}
//其他 file
else if ("file".equals(uri.getScheme())) {
console.log("file")
return uri.getPath() as string;
}
}
return ""
}
function isExternalStorageDocument(uri : Uri) : boolean {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
function isDownloadsDocument(uri : Uri) : boolean {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
function isMediaDocument(uri : Uri) : boolean {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
function getDataColumn(context : Context, uri : Uri, selection : string | null, selectionArgs : String[] | null) : string {
let path = uri.getPath() as string;
let authroity = uri.getAuthority();
let sdPath = Environment.getExternalStorageDirectory().getAbsolutePath() as string;
if (!path.startsWith(sdPath)) {
let sepIndex = path.indexOf(File.separator, 1);
if (sepIndex == -1) {
path = '';
} else {
path = sdPath + path.substring(sepIndex);
}
}
if (path == '' || !new File(path).exists()) {
let resolver = context.getContentResolver();
let projection = arrayOf<string>(MediaStore.MediaColumns.DATA);
const _selectionArgs = selectionArgs != null ? selectionArgs.toTypedArray() : null;
let cursor = resolver.query(uri, projection, selection, _selectionArgs, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
try {
var index = cursor.getColumnIndexOrThrow(projection[0]);
if (index != -1) {
path = cursor.getString(index);
}
} catch (e) {
console.log(e);
path = '';
} finally {
cursor?.close();
}
}
}
}
return path;
}
function getFileName(context : Context, uri : Uri) : string {
let projection = arrayOf(MediaStore.Images.ImageColumns.DISPLAY_NAME)
let cursor = context.getContentResolver().query(uri, projection, null, null, null)
try {
if (cursor != null && cursor.moveToFirst()) {
let name_col_index = cursor.getColumnIndex(projection[0]);
return cursor.getString(name_col_index);
}
} catch (e) {
console.log(e);
} finally {
cursor?.close()
}
return ""
}
function saveFileFromUri(context : Context, uri : Uri) : string {
let file : File;
const contentResolver : ContentResolver = context.getContentResolver();
const cursor : Cursor | null = contentResolver.query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
const displayName = getFileName(context, uri);
try {
const is = contentResolver.openInputStream(uri);
if (is != null) {
const file1 : File = new File(context.getExternalCacheDir()?.getAbsolutePath() + "/" + System.currentTimeMillis());
if (!file1.exists()) {
file1.mkdir();
}
const cache : File = new File(file1.getPath(), displayName);
const fos = new FileOutputStream(cache);
console.log(fos);
FileUtils.copy(is, fos);
file = cache;
fos.close();
is.close();
return file.getAbsolutePath();
}
} catch (e) {
console.log(e);
}
}
return ""
}