index.uts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. // index.uts
  2. // 引用android api
  3. import { UTSAndroid } from "io.dcloud.uts";
  4. import ActivityCompat from "androidx.core.app.ActivityCompat";
  5. import { Context, Intent, ContentUris, ContentResolver } from "android.content";
  6. import { Settings } from "android.provider";
  7. import Uri from "android.net.Uri";
  8. import FileUtils from "android.os.FileUtils";
  9. import { DocumentsContract, MediaStore } from "android.provider";
  10. import { File, FileOutputStream } from "java.io";
  11. import Activity from "android.app.Activity";
  12. import Manifest from "android.Manifest";
  13. import Cursor from "android.database.Cursor";
  14. import { Build, Environment } from "android.os";
  15. type InfoOptions = {
  16. scope?:string,
  17. permission ?: boolean,
  18. mimetype?:string,
  19. success ?: (res : object) => void
  20. fail ?: (res : object) => void
  21. complete ?: (res : object) => void
  22. }
  23. export default function fileSelect(options : InfoOptions) {
  24. UTSAndroid.onAppActivityRequestPermissionsResult((requestCode : number,
  25. permissions : MutableList<string>,
  26. grantResults : MutableList<number>) => {
  27. UTSAndroid.offAppActivityRequestPermissionsResult();
  28. if ((requestCode !== 1001) && (grantResults[0] === -1)) {
  29. options.fail?.({
  30. code: "1001",
  31. errMsg: 'fileselect:fail',
  32. detail:"未授权文件读取权限"
  33. })
  34. const permission=options.permission;
  35. if(permission!=null&&permission){
  36. const intent = new Intent();
  37. intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
  38. const uri = Uri.fromParts("package", UTSAndroid.getUniActivity()?.getPackageName(), "");
  39. intent.setData(uri);
  40. UTSAndroid.getUniActivity()?.startActivity(intent);
  41. }
  42. } else {
  43. fileSelectStart(options);
  44. }
  45. });
  46. // 请求权限
  47. ActivityCompat.requestPermissions(UTSAndroid.getUniActivity()!, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1001)
  48. }
  49. function fileSelectStart(options : InfoOptions) {
  50. const FILE_SELECT_REQUEST_CODE = 110
  51. const context = UTSAndroid.getAppContext();
  52. if (context != null) {
  53. if(options.scope!=null){
  54. let strPath=options.scope
  55. strPath=strPath?.replaceAll("/","%2F")
  56. console.log(strPath);
  57. let uri1:Uri = Uri.parse("content://com.android.externalstorage.documents/document/primary%3A"+strPath);
  58. let intent1:Intent = new Intent(Intent.ACTION_GET_CONTENT);
  59. intent1.addCategory(Intent.CATEGORY_OPENABLE);
  60. if(options.mimetype!=null){
  61. intent1.setType(options.mimetype);
  62. }else{
  63. intent1.setType("*/*");
  64. }
  65. intent1.putExtra(DocumentsContract.EXTRA_INITIAL_URI, uri1);
  66. UTSAndroid.getUniActivity()?.startActivityForResult(intent1, FILE_SELECT_REQUEST_CODE);
  67. }else{
  68. const intent = new Intent(Intent.ACTION_GET_CONTENT);
  69. intent.setType("*/*");
  70. intent.addCategory(Intent.CATEGORY_OPENABLE);
  71. if(options.mimetype!=null){
  72. intent.setType(options.mimetype);
  73. }
  74. UTSAndroid.getUniActivity()?.startActivityForResult(intent, FILE_SELECT_REQUEST_CODE)
  75. }
  76. UTSAndroid.onAppActivityResult((requestCode : Int, resultCode : Int, data ?: Intent) => {
  77. // let eventName = "onAppActivityResult - requestCode:" + requestCode + " -resultCode:"+resultCode + " -data:"+JSON.stringify(data);
  78. UTSAndroid.offAppActivityResult();
  79. if (requestCode == FILE_SELECT_REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) {
  80. const fileUri = data.getData();
  81. if (fileUri != null) {
  82. // console.log('文件选择器:【文件相对路径】', fileUri.getPath());
  83. let path = getRealPathFromURI(context, fileUri)
  84. const file = new File(path)
  85. if (file.exists()) {
  86. let upLoadFilePath = file.toString();
  87. let upLoadFileName = file.getName();
  88. let fileSize = file.length();
  89. const extIdx= upLoadFilePath.lastIndexOf(".");
  90. let fileType =extIdx!=-1?upLoadFilePath.substring(extIdx+1):""
  91. const res = {
  92. code: "0",
  93. filePath: upLoadFilePath,
  94. fileName: upLoadFileName,
  95. fileSize:fileSize,
  96. fileType:fileType,
  97. errMsg: 'fileselect:ok',
  98. detail:"文件读取成功"
  99. }
  100. options.success?.(res)
  101. options.complete?.(res)
  102. } else {
  103. const res2 = {
  104. code: "1002",
  105. errMsg: 'fileselect:fail',
  106. detail:"文件不存在"
  107. }
  108. options.fail?.(res2)
  109. options.complete?.(res2)
  110. }
  111. }
  112. }
  113. });
  114. } else {
  115. const res3 = {
  116. code: "1002",
  117. errMsg: 'fileselect:fail',
  118. detail:"文件不存在"
  119. }
  120. options.fail?.(res3)
  121. options.complete?.(res3)
  122. }
  123. }
  124. function getRealPathFromURI(context : Context, uri : Uri) : string {
  125. const isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
  126. //4.4以下的版本:不支持
  127. //大于4.4
  128. // DocumentProvider
  129. if (isKitKat) {
  130. if (DocumentsContract.isDocumentUri(context, uri)) {
  131. if (isExternalStorageDocument(uri)) {
  132. const docId : string = DocumentsContract.getDocumentId(uri);
  133. const split : string[] = docId.split(":");
  134. console.log(docId, split);
  135. if ("primary".equals(split[0])) {
  136. return Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + split[1];
  137. } else {
  138. return "/storage/" + split[0] + "/" + split[1]
  139. }
  140. }
  141. // DownloadsProvider
  142. else if (isDownloadsDocument(uri)) {
  143. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
  144. return saveFileFromUri(context, uri)
  145. }
  146. const downloadPath: string = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
  147. const fileName:string = getFileName(context, uri);
  148. return downloadPath+"/"+fileName
  149. }
  150. // MediaProvider
  151. else if (isMediaDocument(uri)) {
  152. let docId : string = DocumentsContract.getDocumentId(uri);
  153. let split : string[] = docId.split(":");
  154. let type : string = split[0];
  155. let contentUri : Uri | null = null;
  156. if ("image".equals(type)) {
  157. contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
  158. } else if ("video".equals(type)) {
  159. contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
  160. } else if ("audio".equals(type)) {
  161. contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
  162. }
  163. else if ("document".equals(type)) {
  164. // 安卓系统版本大于等于10
  165. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
  166. return saveFileFromUri(context, uri)
  167. }
  168. return ""
  169. }
  170. const selection : string = "_id=?";
  171. const selectionArgs : String[] = [split[1]];
  172. if (contentUri != null) {
  173. return getDataColumn(context, contentUri, selection, selectionArgs);
  174. }
  175. }
  176. }
  177. //其他 content
  178. else if ("content".equals(uri.getScheme())) {
  179. return getDataColumn(context, uri, null, null);
  180. }
  181. //其他 file
  182. else if ("file".equals(uri.getScheme())) {
  183. return uri.getPath() as string;
  184. }
  185. }
  186. return ""
  187. }
  188. function isExternalStorageDocument(uri : Uri) : boolean {
  189. return "com.android.externalstorage.documents".equals(uri.getAuthority());
  190. }
  191. function isDownloadsDocument(uri : Uri) : boolean {
  192. return "com.android.providers.downloads.documents".equals(uri.getAuthority());
  193. }
  194. function isMediaDocument(uri : Uri) : boolean {
  195. return "com.android.providers.media.documents".equals(uri.getAuthority());
  196. }
  197. function getDataColumn(context : Context, uri : Uri, selection : string | null, selectionArgs : String[] | null) : string {
  198. let column = "_data";
  199. let projection = arrayOf<string>(column)
  200. let cursor : Cursor | null = null;
  201. const _selectionArgs = selectionArgs != null ? selectionArgs.toTypedArray() : null
  202. try {
  203. cursor = context.getContentResolver().query(uri, projection, selection, _selectionArgs, null);
  204. if (cursor != null && cursor.moveToFirst()) {
  205. const column_index = cursor.getColumnIndexOrThrow(column);
  206. return cursor.getString(column_index);
  207. }
  208. } catch (e) {
  209. console.log(e);
  210. } finally {
  211. if (cursor != null) {
  212. cursor.close();
  213. }
  214. }
  215. return "";
  216. }
  217. function getFileName(context : Context, uri : Uri) : string {
  218. let projection = arrayOf(MediaStore.Images.ImageColumns.DISPLAY_NAME)
  219. let cursor = context.getContentResolver().query(uri, projection, null, null, null)
  220. try {
  221. if (cursor != null && cursor.moveToFirst()) {
  222. let name_col_index = cursor.getColumnIndex(projection[0])
  223. return cursor.getString(name_col_index)
  224. }
  225. } catch (e) {
  226. console.log(e);
  227. } finally {
  228. cursor?.close()
  229. }
  230. return ""
  231. }
  232. function saveFileFromUri(context : Context, uri : Uri) : string {
  233. let file : File;
  234. const contentResolver : ContentResolver = context.getContentResolver();
  235. const cursor : Cursor | null = contentResolver.query(uri, null, null, null, null);
  236. if (cursor != null && cursor.moveToFirst()) {
  237. const displayName = getFileName(context, uri)
  238. try {
  239. const is = contentResolver.openInputStream(uri);
  240. if (is != null) {
  241. const file1 : File = new File(context.getExternalCacheDir()?.getAbsolutePath() + "/" + System.currentTimeMillis());
  242. if (!file1.exists()) {
  243. file1.mkdir();
  244. }
  245. const cache : File = new File(file1.getPath(), displayName);
  246. const fos = new FileOutputStream(cache);
  247. FileUtils.copy(is, fos);
  248. file = cache;
  249. fos.close();
  250. is.close();
  251. return file.getAbsolutePath();
  252. }
  253. } catch (e) {
  254. console.log(e);
  255. }
  256. }
  257. return ""
  258. }