How to search file inside a specific folder in google API v3

Viewed 10850

As i am using v3 of google api,So instead of using parent and chidren list i have to use fileList, So now i want to search list of file inside a specific folder. So someone can suggest me what to do?

Here is the code i am using to search the file :

private String searchFile(String mimeType,String fileName) throws IOException{
    Drive driveService = getDriveService();
    String fileId = null;
    String pageToken = null;
    do {
        FileList result = driveService.files().list()
                .setQ(mimeType)
                .setSpaces("drive")
                .setFields("nextPageToken, files(id, name)")
                .setPageToken(pageToken)
                .execute();
        for(File f: result.getFiles()) {
            System.out.printf("Found file: %s (%s)\n",
                    f.getName(), f.getId());
            if(f.getName().equals(fileName)){
                //fileFlag++;
                fileId = f.getId();
            }
        }
        pageToken = result.getNextPageToken();
    } while (pageToken != null);

    return fileId;
}

But in this method it giving me all the files that are generated which i don't want.I want to create a FileList which will give file inside a specific folder.

4 Answers

It is now possible to do it with the term parents in q parameter in drives:list. For example, if you want to find all spreadsheets in a folder with id folder_id you can do so using the following q parameter (I am using python in my example):

q="mimeType='application/vnd.google-apps.spreadsheet' and parents in '{}'".format(folder_id)

Remember that you should find out the id of the folder files inside of which you are looking for. You can do this using the same drives:list.

More information on drives:list method can be seen here, and you can read more about other terms you can put to q parameter here.

To search in a specific directory you have to specify the following:

q : name = '2021' and mimeType = 'application/vnd.google-apps.folder' and '1fJ9TFZOe8G9PUMfC2Ts06sRnEPJQo7zG' in parents

This examples search a folder called "2021" into folder with 1fJ9TFZOe8G9PUMfC2Ts06sRnEPJQo7zG

In my case, I'm writing a code in c++ and the request url would be:

string url = "https://www.googleapis.com/drive/v3/files?q=name+%3d+%272021%27+and+mimeType+%3d+%27application/vnd.google-apps.folder%27+and+trashed+%3d+false+and+%271fJ9TFZOe8G9PUMfC2Ts06sRnEPJQo7zG%27+in+parents";
Related