How to browse all files in a specific directory?

試著忘記壹切 提交于 2019-12-02 23:11:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!