Create and populate folders

Folders are files that only contain metadata and can be used to organize files in Google Drive. Specifically,

  • a folder is a file with the MIME type application/vnd.google-apps.folder and with no extension.
  • you can use the alias root to refer to the root folder anywhere a file ID is provided.

This guide explains how to perform some basic folder-related tasks.

Create a folder

To create a folder, use the files.create method with the application/vnd.google-apps.folder MIME type and a title. The following code snippet shows how to create a folder using a client library:

Java

File fileMetadata = new File();
fileMetadata.setName("Invoices");
fileMetadata.setMimeType("application/vnd.google-apps.folder");

File file = driveService.files().create(fileMetadata)
    .setFields("id")
    .execute();
System.out.println("Folder ID: " + file.getId());

Python

file_metadata = {
    'name': 'Invoices',
    'mimeType': 'application/vnd.google-apps.folder'
}
file = drive_service.files().create(body=file_metadata,
                                    fields='id').execute()
print 'Folder ID: %s' % file.get('id')

Node.js

var fileMetadata = {
  'name': 'Invoices',
  'mimeType': 'application/vnd.google-apps.folder'
};
drive.files.create({
  resource: fileMetadata,
  fields: 'id'
}, function (err, file) {
  if (err) {
    // Handle error
    console.error(err);
  } else {
    console.log('Folder Id: ', file.id);
  }
});

Insert a file in a folder

To insert a file in a folder, use the files.create method and specify the folder ID in the parents property of the file. The following code snippet shows how to insert (upload) a file into a specific folder using a client library:

Java

String folderId = "0BwwA4oUTeiV1TGRPeTVjaWRDY1E";
File fileMetadata = new File();
fileMetadata.setName("photo.jpg");
fileMetadata.setParents(Collections.singletonList(folderId));
java.io.File filePath = new java.io.File("files/photo.jpg");
FileContent mediaContent = new FileContent("image/jpeg", filePath);
File file = driveService.files().create(fileMetadata, mediaContent)
    .setFields("id, parents")
    .execute();
System.out.println("File ID: " + file.getId());

Python

folder_id = '0BwwA4oUTeiV1TGRPeTVjaWRDY1E'
file_metadata = {
    'name': 'photo.jpg',
    'parents': [folder_id]
}
media = MediaFileUpload('files/photo.jpg',
                        mimetype='image/jpeg',
                        resumable=True)
file = drive_service.files().create(body=file_metadata,
                                    media_body=media,
                                    fields='id').execute()
print 'File ID: %s' % file.get('id')

Node.js

var folderId = '0BwwA4oUTeiV1TGRPeTVjaWRDY1E';
var fileMetadata = {
  'name': 'photo.jpg',
  parents: [folderId]
};
var media = {
  mimeType: 'image/jpeg',
  body: fs.createReadStream('files/photo.jpg')
};
drive.files.create({
  resource: fileMetadata,
  media: media,
  fields: 'id'
}, function (err, file) {
  if (err) {
    // Handle error
    console.error(err);
  } else {
    console.log('File Id: ', file.id);
  }
});

The parents property can be used when creating a folder and subfolders.

Moving files between folders

To add or remove parents for an existing file, use files.update method with the addParents and removeParents query parameters. The following code snippet move a file between folders using a client library::

Java

String fileId = "1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ";
String folderId = "0BwwA4oUTeiV1TGRPeTVjaWRDY1E";
// Retrieve the existing parents to remove
File file = driveService.files().get(fileId)
    .setFields("parents")
    .execute();
StringBuilder previousParents = new StringBuilder();
for (String parent : file.getParents()) {
  previousParents.append(parent);
  previousParents.append(',');
}
// Move the file to the new folder
file = driveService.files().update(fileId, null)
    .setAddParents(folderId)
    .setRemoveParents(previousParents.toString())
    .setFields("id, parents")
    .execute();

Python

file_id = '1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ'
folder_id = '0BwwA4oUTeiV1TGRPeTVjaWRDY1E'
# Retrieve the existing parents to remove
file = drive_service.files().get(fileId=file_id,
                                 fields='parents').execute()
previous_parents = ",".join(file.get('parents'))
# Move the file to the new folder
file = drive_service.files().update(fileId=file_id,
                                    addParents=folder_id,
                                    removeParents=previous_parents,
                                    fields='id, parents').execute()

Node.js

fileId = '1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ'
folderId = '0BwwA4oUTeiV1TGRPeTVjaWRDY1E'
// Retrieve the existing parents to remove
drive.files.get({
  fileId: fileId,
  fields: 'parents'
}, function (err, file) {
  if (err) {
    // Handle error
    console.error(err);
  } else {
    // Move the file to the new folder
    var previousParents = file.parents.join(',');
    drive.files.update({
      fileId: fileId,
      addParents: folderId,
      removeParents: previousParents,
      fields: 'id, parents'
    }, function (err, file) {
      if (err) {
        // Handle error
      } else {
        // File moved.
      }
    });
  }
});

Envoyer des commentaires concernant…

Besoin d'aide ? Consultez notre page d'assistance.