Google Drive SDK

Files: update

Requires authorization

Updates file metadata and/or content. See an example.

Request

HTTP Request

PUT https://www.googleapis.com/drive/v1/files/id

Parameters

Parameter Name Value Description
Required Parameters
id string The ID for the file in question.
Optional Parameters
newRevision boolean Whether a blob upload should create a new revision. If not set or false, the blob data in the current head revision will be replaced.
updateModifiedDate boolean Controls updating the modified date of the file. If true, the modified date will be updated to the current time, regardless of whether other changes are being made. If false, the modified date will only be updated to the current time if other changes are also being made (changing the title, for example). Default value is false.
updateViewedDate boolean Whether to update the view date after successfully updating the file.

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.file

Request Body

In the request body, supply a Files resource.

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.client.http.FileContent;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;

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

public class MyClass {

  // ...

  /**
   * Update an existing file's metadata and content.
   *
   * @param service Drive API service instance.
   * @param fileId ID of the file to update.
   * @param newTitle New title for the file.
   * @param newDescription New description for the file.
   * @param newMimeType New MIME type for the file.
   * @param newFilename Filename of the new content to upload.
   * @param newRevision Whether or not to create a new revision for this
   *        file.
   * @return Updated file metadata if successful, {@code null} otherwise.
   */
  private static File updateFile(Drive service, String fileId, String newTitle,
      String newDescription, String newMimeType, String newFilename, boolean newRevision) {
    try {
      // First retrieve the file from the API.
      File file = service.files().get(fileId).execute();

      // File's new metadata.
      file.setTitle(newTitle);
      file.setDescription(newDescription);
      file.setMimeType(newMimeType);

      // File's new content.
      java.io.File fileContent = new File(newFilename);
      FileContent mediaContent = new FileContent(newMimeType, fileContent);

      // Send the request to the API.
      File updatedFile = service.files().update(fileId, file, mediaContent).execute();

      return updatedFile;
    } catch (IOException e) {
      System.out.println("An error occurred: " + e);
      return null;
    }
  }

  // ...
}

.NET

Uses the .NET client library

using Google.Apis.Drive.v1;
using Google.Apis.Drive.v1.Data;

// ...

public class MyClass {

  // ...

  /// <summary> 
  /// Update an existing file's metadata.
  /// </summary>
  /// <param name="service">Drive API service instance.</param>
  /// <param name="fileId">ID of the file to update.</param>
  /// <param name="newTitle">New title for the file.</param>
  /// <param name="newDescription">New description for the file.</param>
  /// <param name="newMimeType">New MIME type for the file.</param>
  /// <param name="newRevision">Whether or not to create a new revision for this file.</param>
  /// <returns>Updated file metadata, null is returned if an API error occurred.</returns>
  private static File updateMetadata(DriveService service, String fileId, String newTitle,
      String newDescription, String newMimeType, bool newRevision) {
      try {
          // First retrieve the file from the API.
          File file = service.Files.Get(fileId).Fetch();

          file.Title = newTitle;
          file.Description = newDescription;
          file.MimeType = newMimeType;

          // Update the file's metadata.
          FilesResource.UpdateRequest request = service.Files.Update(file, fileId);
          request.NewRevision = newRevision;
          File updatedFile = request.Fetch();

          return updatedFile;
      } catch (Exception e) {
          Console.WriteLine("An error occurred: " + e.Message);
          return null;
      }
  }

  /// <summary>
  /// Update an existing file's content.
  /// </summary>
  /// <param name="service">Drive API service instance.</param>
  /// <param name="fileId">ID of the file to update.</param>
  /// <param name="newMimeType">New MIME type for the file.</param>
  /// <param name="newFilename">Filename of the new content to upload.</param>
  /// <param name="newRevision">Whether or not to create a new revision for this file.</param>
  /// <returns>Updated file metadata, null is returned if an API error occurred.</returns>
  private static File updateFile(DriveService service, String fileId, String newMimeType, String newFilename, bool newRevision) {
      try {
           HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(
              "https://www.googleapis.com/upload/drive/v1/files/"
              + fileId + "?newRevision=" + newRevision);
          request.Method = "PUT";

          Stream memStream = new MemoryStream();
          FileStream stream = new FileStream(newFilename, FileMode.Open, FileAccess.Read);
          byte[] buffer = new byte[1024];
          int bytesRead = 0;

          while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0) {
              memStream.Write(buffer, 0, bytesRead);
          }

          stream.Close();

          request.ContentLength = memStream.Length;
          if (!string.IsNullOrEmpty(newMimeType)) {
              request.ContentType = newMimeType;
          }
          auth.ApplyAuthenticationToRequest(request);

          memStream.Position = 0;
          byte[] tempBuffer = new byte[memStream.Length];
          memStream.Read(tempBuffer, 0, tempBuffer.Length);
          memStream.Close();

          Stream requestStream = request.GetRequestStream();
          requestStream.Write(tempBuffer, 0, tempBuffer.Length);
          requestStream.Close();

          IResponse response = new Response(request.GetResponse());
          File file = service.DeserializeResponse<File>(response);

          // Uncomment the following line to print the File ID.
          // Console.WriteLine("File ID: " + file.Id);

          return file;
      } catch (Exception e) {
          Console.WriteLine("An error occurred: " + e.Message);
          return null;
      }
  }

  //...

}

PHP

Uses the PHP client library

/**
 * Update an existing file's metadata and content.
 *
 * @param apiDriveService $service Drive API service instance.
 * @param string $fileId ID of the file to update.
 * @param string $newTitle New title for the file.
 * @param string $newDescription New description for the file.
 * @param string $newMimeType New MIME type for the file.
 * @param string $newFilename Filename of the new content to upload.
 * @param bool $newRevision Whether or not to create a new revision for this file.
 * @return DriveFile The updated file. NULL is returned if an API error occurred.
 */
function updateFile($service, $fileId, $newTitle, $newDescription, $newMimeType, $newFileName, $newRevision) {
  try {
    // First retrieve the file from the API.
    $file = $service->files->get($fileId);

    // File's new metadata.
    $file->setTitle($newTitle);
    $file->setDescription($newDescription);
    $file->setMimeType($newMimeType);

    // File's new content.
    $data = file_get_contents($newFileName);

    $additionalParams = array(
        'newRevision' => $newRevision,
        'data' => $data,
        'mimeType' => $newMimeType
    );

    // Send the request to the API.
    $updatedFile = $service->files->update($fileId, $file, $additionalParams);
    return $updatedFile;
  } catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
  }
}

Python

Uses the Python client library

from apiclient import errors
from apiclient.http import MediaFileUpload
# ...

def update_file(service, file_id, new_title, new_description, new_mime_type,
                new_filename, new_revision):
  """Update an existing file's metadata and content.

  Args:
    service: Drive API service instance.
    file_id: ID of the file to update.
    new_title: New title for the file.
    new_description: New description for the file.
    new_mime_type: New MIME type for the file.
    new_filename: Filename of the new content to upload.
    new_revision: Whether or not to create a new revision for this file.
  Returns:
    Updated file metadata if successful, None otherwise.
  """
  try:
    # First retrieve the file from the API.
    file = service.files().get(id=file_id).execute()

    # File's new metadata.
    file['title'] = new_title
    file['description'] = new_description
    file['mimeType'] = new_mime_type

    # File's new content.
    media_body = MediaFileUpload(
        new_filename, mimetype=new_mime_type, resumable=True)

    # Send the request to the API.
    updated_file = service.files().update(
        id=file_id,
        body=file,
        newRevision=new_revision,
        media_body=media_body).execute()
    return updated_file
  except errors.HttpError, error:
    print 'An error occurred: %s' % error
    return None

Ruby

Uses the Ruby client library

##
# Update a file
#
# @param [Google::APIClient] client
#   Authorized client instance
# @param [String] file_id
#   ID of file to update
# @param [String] title
#   New title of file to insert
# @param [String] description
#   New description of file to insert
# @param [String] mime_type
#   New MIME type of file to insert
# @param [TrueClass, FalseClass] new_revision?
#  Whether or not to create a new revision of the file	
# @param [String] file_name
#  File content to upload
# @return [Google::APIClient::Schema::Drive::V1::File]
#   File if updated, nil otherwise
def update_file(client, title, description, mime_type,
                new_revision?, file_name)
  drive = client.discovered_api('drive', 'v1')
  # Retrieve existing metadata
  result = client.execute(
    :api_method => drive.files.get,
    :parameters => { 'id' => file_id })
  if result.status == 200
    file = result.data
    file.title = title
    file.description = description
    file.mime_type = mime_type
    media = Google::APIClient::UploadIO.new(file_name, mime_type)
    result = client.execute(
      :api_method => drive.files.update,
      :body_object => file,
      :media => media,
      :parameters => { 'id' => file_id, 
                       'newRevision' => new_revision?,
                       'uploadType' => 'multipart',
                       'alt' => 'json' })
    if result.status == 200
     return result.data
    end
  end
  puts "An error occurred: #{result.data['error']['message']}"
  return nil
end

Authentication required

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

Signing you in...

Google Developers needs your permission to do that.