Google Drive API - get list of files including folders

。_饼干妹妹 提交于 2020-01-02 08:50:43

问题


I need to list all images in a users drive cloud.

I use https://www.googleapis.com/drive/v2/files with the correct filter to query all images. I need to group the result in my app in folders. I know a file can have multiple parents, that's fine.

I would like to avoid making and calls (for every single file a single call) to get a files folder via https://developers.google.com/drive/v2/reference/files/get using the parent id from the first call.

Is there a network friendly way to get all files inclusive there folders?

EDIT

A simple solution would be to get all folders with ids in one query and lookup folder names in this result. Maybe that's somehow possible?


回答1:


As you answered yourself in the comments above (but you can't match names, you have to match IDs; names aren't unique).

Step 1: get all your folders in one shot (paging results, filtering unneeded fields, skipping the trashed ones):

  private static Drive mGOOSvc;
  ....
  static ArrayList<ContentValues> getFolders() {
    ArrayList<ContentValues> cvs = new ArrayList<>();
    if (mGOOSvc != null) try {
      Drive.Files.List qry = mGOOSvc.files().list()
        .setQ("mimeType = 'application/vnd.google-apps.folder'")
        .setFields("items(id,labels/trashed,parents/id,title),nextPageToken");
      String npTok = null;
      if (qry != null) do {
        FileList gLst = qry.execute();
        if (gLst != null) {
          for (File gFl : gLst.getItems()) {
            if (gFl.getLabels().getTrashed()) continue;
            for (ParentReference parent : gFl.getParents())
              cvs.add(newContentValues(gFl.getTitle(), gFl.getId(), parent.getId()));
          }
          npTok = gLst.getNextPageToken();
          qry.setPageToken(npTok);
        }
      } while (npTok != null && npTok.length() > 0);
    } catch (Exception e) { /* handle Exceptions */ }
    return cvs;
  }

Step 2: Parse the resulting ArrayList to build the tree structure (match ParentIds, handle multiple parents)

Step 3: Do the same for files with mime type ""image/jpeg", "image/png", ... "whatever img mimetype" (just modify the code above to get files) and parse again.

Of course the 'execute()' method will produce exceptions that should be handled as pointed out here.

... and you can take the 'not so network friendly' approach of iterating down the folder tree as seen in the 'testTree()' method here. Recursion is necessary if you have no knowledge how deep your tree structure is.

Good Luck



来源:https://stackoverflow.com/questions/34084850/google-drive-api-get-list-of-files-including-folders

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