Google Drive SDK

Files: copy

Requires authorization

Creates a copy of the specified file. Try it now or see an example.

Request

HTTP request

POST https://www.googleapis.com/drive/v2/files/fileId/copy

Parameters

Parameter name Value Description
Path parameters
fileId string The ID of the file to copy.
Optional query parameters
convert boolean Whether to convert this file to the corresponding Google Docs format. (Default: false)
ocr boolean Whether to attempt OCR on .jpg, .png, .gif, or .pdf uploads. (Default: false)
ocrLanguage string If ocr is true, hints at the language to use. Valid values are ISO 639-1 codes.
pinned boolean Whether to pin the head revision of the new copy. (Default: false)
timedTextLanguage string The language of the timed text.
timedTextTrackName string The timed text track name.
visibility string The visibility of the new file. This parameter is only relevant when the source is not a native Google Doc and convert=false.

Acceptable values are:
  • "DEFAULT": The visibility of the new file is determined by the user's default visibility/sharing policies. (default)
  • "PRIVATE": The new file will be visible to only the owner.

Authorization

This request requires authorization with at least one of the following scopes (read more about authentication and authorization).

Scope
https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.file
https://www.googleapis.com/auth/drive.appdata
https://www.googleapis.com/auth/drive.apps.readonly

Request body

In the request body, supply a Files resource with the following properties:

Property name Value Description Notes
Optional Properties
description string A short description of the file. writable
indexableText.text string The text to be indexed for this file. writable
labels.hidden boolean Deprecated. writable
labels.restricted boolean Whether viewers are prevented from downloading this file. writable
labels.starred boolean Whether this file is starred by the user. writable
labels.trashed boolean Whether this file has been trashed. writable
labels.viewed boolean Whether this file has been viewed by this user. writable
lastViewedByMeDate datetime Last time this file was viewed by the user (formatted RFC 3339 timestamp). writable
modifiedDate datetime Last time this file was modified by anyone (formatted RFC 3339 timestamp). This is only mutable on update when the setModifiedDate parameter is set. writable
parents[] list Collection of parent folders which contain this file.

Setting this field will put the file in all of the provided folders. On insert, if no folders are provided, the file will be placed in the default root folder.

writable
properties[] list The list of properties. This is a write-only field. writable
title string The title of the this file. Used to identify file or folder name. writable
writersCanShare boolean Whether writers can share the document with other users. writable

Response

If successful, this method returns a Files resource in the response body.

Examples

Note: The code examples available for this method do not represent all supported programming languages (see the client libraries page for a list of supported languages).

Java

Uses the Java client library

import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;

import java.io.IOException;
// ...

public class MyClass {

  // ...

  /**
   * Copy an existing file.
   *
   * @param service Drive API service instance.
   * @param originFileId ID of the origin file to copy.
   * @param copyTitle Title of the copy.
   * @return The copied file if successful, {@code null} otherwise.
   */
  private static File copyFile(Drive service, String originFileId,
      String copyTitle) {
    File copiedFile = new File();
    copiedFile.setTitle(copyTitle);
    try {
      return service.files().copy(originFileId, copiedFile).execute();
    } catch (IOException e) {
      System.out.println("An error occurred: " + e);
    }
    return null;
  }

  // ...

}

.NET

Uses the .NET client library

using Google.Apis.Drive.v2;
using Google.Apis.Drive.v2.Data;

using System.Net;
// ...

public class MyClass {

  // ...

  /// <summary>
  /// Copy an existing file.
  /// </summary>
  /// <param name="service">Drive API service instance.</param>
  /// <param name="originFileId">ID of the origin file to copy.</param>
  /// <param name="copyTitle">Title of the copy.</param>
  /// <returns>The copied file, null is returned if an API error occurred</returns>
  public static File CopyFile(DriveService service, String originFileId, String copyTitle) {
    File copiedFile = new File();
    copiedFile.Title = copyTitle;
    try {
      return service.Files.Copy(copiedFile, originFileId).Fetch();
    } catch (Exception e) {
      Console.WriteLine("An error occurred: " + e.Message);
    }
    return null;
  }

  // ...

}

PHP

Uses the PHP client library

/**
 * Copy an existing file.
 *
 * @param Google_DriveService $service Drive API service instance.
 * @param String $originFileId ID of the origin file to copy.
 * @param String $copyTitle Title of the copy.
 * @return DriveFile The copied file. NULL is returned if an API error occurred.
 */
function copyFile($service, $originFileId, $copyTitle) {
  $copiedFile = new Google_DriveFile();
  $copiedFile->setTitle($copyTitle);
  try {
    return $service->files->copy($originFileId, $copiedFile);
  } catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
  }
  return NULL;
}

Python

Uses the Python client library

from apiclient import errors
# ...

def copy_file(service, origin_file_id, copy_title):
  """Copy an existing file.

  Args:
    service: Drive API service instance.
    origin_file_id: ID of the origin file to copy.
    copy_title: Title of the copy.

  Returns:
    The copied file if successful, None otherwise.
  """
  copied_file = {'title': copy_title}
  try:
    return service.files().copy(
        fileId=origin_file_id, body=copied_file).execute()
  except errors.HttpError, error:
    print 'An error occurred: %s' % error
  return None

Ruby

Uses the Ruby client library

##
# Copy an existing file
#
# @param [Google::APIClient] client
#   Authorized client instance
# @param [String] origin_file_id
#   ID of the origin file to copy
# @param [String] copy_title
#   Title of the copy
# @return [Google::APIClient::Schema::Drive::V2::File]
#   The copied file if successful, nil otherwise
def copy_file(client, origin_file_id, copy_title)
  drive = client.discovered_api('drive', 'v2')
  copied_file = drive.files.copy.request_schema.new({
    'title' => copy_title
  })
  result = client.execute(
    :api_method => drive.files.copy,
    :body_object => copied_file,
    :parameters => { 'fileId' => origin_file_id })
  if result.status == 200
    return result.data
  else
    puts "An error occurred: #{result.data['error']['message']}"
  end
end

JavaScript

Uses the JavaScript client library

/**
 * Copy an existing file.
 *
 * @param {String} originFileId ID of the origin file to copy.
 * @param {String} copyTitle Title of the copy.
 */
function copyFile(originFileId, copyTitle) {
  var body = {'title': copyTitle};
  var request = gapi.client.drive.files.copy({
    'fileId': originFileId,
    'resource': body
  });
  request.execute(function(resp) {
    console.log('Copy ID: ' + resp.id);
  });
}

Go

Uses the Go client library

import (
  "code.google.com/p/google-api-go-client/drive/v2"
  "fmt"
)

// CopyFile copies a file setting a new title on the copy
func CopyFile(d *drive.Service, fileId string,
    title string) (*drive.File, error) {
  f := &drive.File{Title: title}
  r, err := d.Files.Copy(fileId, f).Do()
  if err != nil {
    fmt.Printf("An error occurred: %v\n", err)
    return nil, err
  }
  return r, nil
}

Objective-C

Uses the Objective-C client library

#import "GTLDrive.h"
// ...

+ (void)copyFileWithService:(GTLServiceDrive *)service
               originFileId:(NSString *)originFileId
                  copyTitle:(NSString *)copyTitle
            completionBlock:(void (^)(GTLDriveFile *, NSError *))completionBlock {
  GTLDriveFile *copiedFile = [GTLDriveFile object];
  copiedFile.title = copyTitle;

  GTLQueryDrive *query =
    [GTLQueryDrive queryForFilesCopyWithObject:copiedFile fileId:originFileId];
  // queryTicket can be used to track the status of the request.
  GTLServiceTicket *queryTicket =
    [service executeQuery:query
        completionHandler:^(GTLServiceTicket *ticket, GTLDriveFile *file,
                            NSError *error) {
          if (error == nil) {
            completionBlock(file, nil);
          } else {
            NSLog(@"An error occurred: %@", error);
            completionBlock(nil, error);
          }
        }];
}

// ...

Try it!

Use the APIs Explorer below to call this method on live data and see the response.

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.