5

I have some data on Google Drive, organized in folders, which I want to propagate on other servers. I have some script for propagating, but I need to download data from google drive. Is there a method for downloading folders via Google Drive API, that is also maintaining whole folder structure?

zerozero7
  • 383
  • 3
  • 4
  • 10

2 Answers2

8

Folders are also files on Google Drive. The only difference is the Mime type. with folders its mimeType = 'application/vnd.google-apps.folder'.

There is no single method that will allow you to download everything with in a folder. Your going to have to do a file.list searching for the files with the parent Id to the file Id of your parent folder using search parameters (TIP: ''1234567' in parents'). This will return a list of the files contained within your folder. Then download each one.

Update from comment you need to loop though each directory or just do a main list of everything on your drive account and process the data locally.

File 1 (folder)
----> File 2 (folder )
--------> File 3 (actually a file)
---->File Four (actually a file)

'File 1' in parents 

returns everything within the file 1 directory. If the mime type of the item returned is a directory (mimeType = 'application/vnd.google-apps.folder') make a request to get its contences

'File 2' in parents

returns everything within the file 2 directory.

Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
  • Thank you. But what about downloading file that is not a direct child of specific folder? `'file_id' in parents` matches only direct children – zerozero7 Dec 19 '16 at 10:53
  • try playing with Not (not 'file_id' in parents) should bring back all files not in that directory. – Linda Lawton - DaImTo Dec 19 '16 at 10:57
  • What I meant is to get `file3` from structure `file1 -> file2 -> file3`, knowing only `file1`. `parents` field in Drive API contains only direct parent – zerozero7 Dec 19 '16 at 11:49
  • 2
    your going to have to make a request for each sub directory. use the results from the first request to request the data from subsequent requests. – Linda Lawton - DaImTo Dec 19 '16 at 12:03
-1
FileList result = service.files().list().setQ("parents='1NzSAZEwAFARWegk42ANrWQrTopWQTdGB'").setSpaces("drive")
                    .setFields("nextPageToken, files(id, name)")
                    .setPageToken(pageToken)
                    .execute();

The parents parameter is the the fileId of the folder you want to download files from. Doing this you can get all files in that particular folder.

gileri
  • 662
  • 8
  • 16
  • Hi, if you want to improve your answer, you can put your code in a code block. It will be more readable. Moreover, the code seems incomplete; for example `pageToken` is not defined, and the folder contents is only listed, not downloaded. Is recursivity handled ? – gileri Aug 23 '22 at 16:35