问题
I'm using Nativescript to build some app, that needs to list and present all files in the phone's gallery. I cannot use any "image picker": It just needs to present the user with all existing images, but doing so through the app.
I was told to use this:
android.os.Environment.DIRECTORY_PICTURES
But this just returns a string "Pictures".
How do i actually access this directory? What Android class deals with "browsing" built-in directories?
The documentation contains countless classes. Could someone point me in the correct direction?
回答1:
Create an instance of Folder
from the absolute path and use .getEntities()
method to read list of files / folders within the particular folder.
import { Folder } from "tns-core-modules/file-system";
const androidPicturesPath = android.os.Environment.getExternalStoragePublicDirectory(
android.os.Environment.DIRECTORY_PICTURES
).toString();
const folder = Folder.fromPath(androidPicturesPath);
folder.getEntities()
.then((entities) => {
// entities is an array of files and folders.
entities.forEach((entity) => {
console.log(entity.name);
});
}).catch((err) => {
// Failed to obtain folder's contents.
console.log(err);
});
Note: Make sure your app has READ_EXTERNAL_STORAGE permission, use nativescript-permissions plugin to acquire the permission at run time.
来源:https://stackoverflow.com/questions/56089951/how-to-browse-all-files-in-a-specific-directory