0%

uniapp获取android文件及相册

uniapp获取android文件及相册

最近在折腾nas,笔者的nas是wd pr4100,是原装系统,没有装黑群晖,西数自带的相册同步软件 没有安装gms,不能使用google play安装,

就找写开源的 相册同步,分别是sycnthingphotoprism 两个都是go开发的, syncthing挺好的,可能是笔者不太会配置,局域网同步速度也很慢,然后研究 pthotprism 这个主要是图片的显示,和ai分组等功能,上传也主要是在web界面上传,有个android客户端,但是不是很好使,然后就想 自己用uniapp做个客户端,后台用photoprism 想法是很好 但是刚开始就遇到问题 记录一下,
uniapp现在用的很多,但是找与原生的navative.js 资料很少 这里笔者 自己android也是很久接触过一点,基本不懂 但是为了解决还是 看了不少原生anroid的代码
这里记录几个与相册文件有关的代码,待完善 只有安卓的

读取单张文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
_openFile() {
// #ifdef APP-PLUS
if (plus.os.name.toLowerCase() != "android") {
uni.showModal({
title: '提示',
content: '仅支持Android平台',
success: function (res) {}
});
return false
}
let that = this
// java 代码来自 http://www.cnblogs.com/panhouye/archive/2017/04/23/6751710.html
let main = plus.android.runtimeMainActivity();
let Intent = plus.android.importClass("android.content.Intent");
// 选择文件

let fileIntent = new Intent(Intent.ACTION_GET_CONTENT)
//fileIntent.setType(“image/*”);//选择图片
//fileIntent.setType(“audio/*”); //选择音频
//fileIntent.setType(“video/*”); //选择视频 (mp4 3gp 是android支持的视频格式)
//fileIntent.setType(“video/*;image/*”);//同时选择视频和图片
//fileIntent.setType(”/*“); //无类型限制 Intent.ACTION_OPEN_DOCUMENT_TREE
fileIntent.setType("*/*");
main.startActivityForResult(fileIntent, 1);
// 获取回调
main.onActivityResult = function (requestCode, resultCode, data) {
let Activity = plus.android.importClass("android.app.Activity");
let ContentUris = plus.android.importClass("android.content.ContentUris");
let Cursor = plus.android.importClass("android.database.Cursor");
let Uri = plus.android.importClass("android.net.Uri");
let Build = plus.android.importClass("android.os.Build");
let Environment = plus.android.importClass("android.os.Environment");
let DocumentsContract = plus.android.importClass("android.provider.DocumentsContract");
let MediaStore = plus.android.importClass("android.provider.MediaStore");
// 给系统导入 contentResolver
let contentResolver = main.getContentResolver()
plus.android.importClass(contentResolver);
// 返回路径
let path = '';
let type = "tree"
if (resultCode == Activity.RESULT_OK) {
let uri = data.getData()
if ("file" == uri.getScheme().toLowerCase()) { //使用第三方应用打开
path = uri.getPath();
return;
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { //4.4以后
path = getPath(this, uri);
} else { //4.4以下下系统调用方法
path = getRealPathFromURI(uri)
}
// 回调
that.$emit('result', path)
}
// 4.4 以上 从Uri 获取文件绝对路径
function getPath(context, uri) {
let isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
let scheme = uri.getScheme().toLowerCase()
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
let docId = DocumentsContract.getDocumentId(uri);
let split = docId.split(":");
let type = split[0];
// 如果是手机内部存储
if ("primary" == type.toLowerCase()) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
} else {
return '/storage/' + type + "/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
let id = DocumentsContract.getDocumentId(uri);
let split = id.split(":");
return split[1]
// console.log(id)
// let contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), id);
// return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
let docId = DocumentsContract.getDocumentId(uri);
let split = docId.split(":");
let type = split[0];
let contentUri = null;
if ("image" == type.toLowerCase()) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video" == type.toLowerCase()) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio" == type.toLowerCase()) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
let selection = "_id=?";
let selectionArgs = [split[1]];
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content" == scheme) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file" == scheme) {
return uri.getPath();
}
}
// 4.4 以下 获取 绝对路径
function getRealPathFromURI(uri) {
let res = null
let proj = [MediaStore.Images.Media.DATA]
let cursor = contentResolver.query(uri, proj, null, null, null);
if (null != cursor && cursor.moveToFirst()) { ;
let column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
cursor.close();
}
return res;
}
// 通过uri 查找出绝对路径
function getDataColumn(context, uri, selection, selectionArgs) {
let cursor = null;
let column = "_data";
let projection = [column];
// let contentResolver = context.getContentResolver()
// plus.android.importClass(contentResolver);
cursor = contentResolver.query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
let column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
}
function isExternalStorageDocument(uri) {
return "com.android.externalstorage.documents" == uri.getAuthority() ? true : false
}
function isDownloadsDocument(uri) {
return "com.android.providers.downloads.documents" == uri.getAuthority() ? true : false
}
function isMediaDocument(uri) {
return "com.android.providers.media.documents" == uri.getAuthority() ? true : false
}
}
// #endif
// #ifndef APP-PLUS
uni.showModal({
title: '提示',
content: '仅支持Android平台',
success: function (res) {

}
});
// #endif
}
读取文件夹

读取文件夹后如何 批量上传文件夹下的文件还没搞明白

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
_openFile() {
// #ifdef APP-PLUS
if (plus.os.name.toLowerCase() != "android") {
uni.showModal({
title: '提示',
content: '仅支持Android平台',
success: function (res) {}
});
return false
}
let that = this
// java 代码来自 http://www.cnblogs.com/panhouye/archive/2017/04/23/6751710.html
let main = plus.android.runtimeMainActivity();
let Intent = plus.android.importClass("android.content.Intent");
let fileIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
fileIntent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
fileIntent.putExtra("android.content.extra.SHOW_ADVANCED", true);
main.startActivityForResult(fileIntent, 1);
// 获取回调
main.onActivityResult = function (requestCode, resultCode, data) {
let Activity = plus.android.importClass("android.app.Activity");
let ContentUris = plus.android.importClass("android.content.ContentUris");
let Cursor = plus.android.importClass("android.database.Cursor");
let Uri = plus.android.importClass("android.net.Uri");

let Environment = plus.android.importClass("android.os.Environment");
let DocumentsContract = plus.android.importClass("android.provider.DocumentsContract");
// 给系统导入 contentResolver
let contentResolver = main.getContentResolver()
plus.android.importClass(contentResolver);
// 返回路径
let path = '';
if (resultCode == Activity.RESULT_OK) {
let uri = data.getData()
path = getTreePath(this, uri)
// 回调
that.$emit('result', path)
}
function getTreePath(context, uri){
console.log(uri.getAuthority())
//uri = DocumentsContract.buildDocumentUriUsingTree(uri, DocumentsContract.getDocumentId(uri))
let docId = DocumentsContract.getTreeDocumentId(uri);
console.log(docId)
let split = docId.split(":");
let type = split[0];
// 如果是手机内部存储
if ("primary" == type.toLowerCase()) {
console.log(Environment.getExternalStorageDirectory() + "/" + split[1])
return Environment.getExternalStorageDirectory() + "/" + split[1];
} else {
return '/storage/' + type + "/" + split[1];
}
}
}
// #endif
// #ifndef APP-PLUS
uni.showModal({
title: '提示',
content: '仅支持Android平台',
success: function (res) {

}
});
// #endif
}
获取相册下的所有图片
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
fGetSavedFileList() {
const main = plus.android.runtimeMainActivity();
const MediaStore = plus.android.importClass('android.provider.MediaStore');
let DocumentsContract = plus.android.importClass("android.provider.DocumentsContract");
const mediaUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
const contentResolver = main.getContentResolver();
plus.android.importClass(contentResolver);
const cursor = contentResolver.query(mediaUri, null, null, null, null);
// 按相片添加时间降序排序
//const cursor = contentResolver.query(mediaUri, null, null, null, MediaStore.Images.Media.DATE_ADDED + 'DESC');

plus.android.importClass(cursor);
const cursorLen = cursor.getCount();

if (cursor === null || cursorLen <= 0) return;

const picList = [];
// while (cursor.moveToNext()) {}
for (let i = 0; i < cursorLen; i++) {
cursor.moveToNext();
const picPath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));

// 创建时间DATE_ADDED 修改时间DATE_MODIFIED
const picDate = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_ADDED));

// 1天内
const filterTime = picDate * 1000 > new Date().getTime() - 24 * 60 * 60 * 1000;
// 拍照
console.log(picPath)
const isDCIM = /DCIM/.test(picPath);
if (filterTime && isDCIM) {
picList.push({
path: picPath,
picDate,
});
}
}
cursor.close();

console.log(99999, cursorLen, picList);
uni.previewImage({
urls: picList.map(({ path }) => path)
});

}
获取根目录下所有文件 不能选择
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
getDownloadLists(){
/*
//应用的download 这里是应用的plus io 但是只能获取应用下的文件
plus.io.requestFileSystem( plus.io.PUBLIC_DOWNLOADS, function( fs ) {
// 可通过fs操作PUBLIC_DOCUMENTS文件系统
console.log(fs.name)
console.log(fs.root.fullPath)
var directoryReader = fs.root.createReader();
directoryReader.readEntries( function( entries ){
console.log(entries.length)
var i;
for( i=0; i < entries.length; i++ ) {
console.log(entries[i].name)
}
}, function ( e ) {
alert( "Request file system failed: " + e.message );
} );
})
*/
var environment = plus.android.importClass("android.os.Environment");
//getExternalStoragePublicDirectory
//var sdRoot = environment.getExternalStoragePublicDirectory(environment.DIRECTORY_DOWNLOADS);//根目录getExternalStorageDirectory
var sdRoot = environment.getExternalStorageDirectory();
var files = plus.android.invoke(sdRoot,"listFiles");
var len = files.length;
for(var i=0; i<len; i++){
var file = files[i];
// 过滤隐藏文件
if(!plus.android.invoke(file,"isHidden")){
// 非隐藏文件执行操作
var name = plus.android.invoke(file,"getName");
console.log(sdRoot+"/"+name)
}
}
}