Google Drive SDK

Files: update

Requires authorization

Updates file metadata and/or content. Try it now or see an example.

This method supports an /upload URI and accepts uploaded media with the following characteristics:

  • Maximum file size: 10GB
  • Accepted Media MIME types: */*

Request

HTTP request

This method provides media upload functionality through two separate URIs. For more details, see the document on media upload.

  • Upload URI, for media upload requests:
    PUT https://www.googleapis.com/upload/drive/v2/files/fileId
  • Metadata URI, for metadata-only requests:
    PUT https://www.googleapis.com/drive/v2/files/fileId

Parameters

Parameter name Value Description
Path parameters
fileId string The ID of the file to update.
Required query parameters
uploadType string The type of upload request to the /upload URI. Acceptable values are:
  • media - Simple upload. Upload the media only, without any metadata.
  • multipart - Multipart upload. Upload both the media and its metadata, in a single request.
  • resumable - Resumable upload. Upload the file in a resumable fashion, using a series of at least two requests where the first request includes the metadata.
Optional query parameters
convert boolean Whether to convert this file to the corresponding Google Docs format. (Default: false)
newRevision boolean Whether a blob upload should create a new revision. If false, the blob data in the current head revision is replaced. If not set or true, a new blob is created as head revision, and previous revisions are preserved (causing increased use of the user's data storage quota). (Default: true)
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 new revision. (Default: false)
setModifiedDate boolean Whether to set the modified date with the supplied modified date. (Default: false)
timedTextLanguage string The language of the timed text.
timedTextTrackName string The timed text track name.
updateViewedDate boolean Whether to update the view date after successfully updating the file. (Default: true)
useContentAsIndexableText boolean Whether to use the content as indexable text. (Default: false)

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.scripts
https://www.googleapis.com/auth/drive.apps.readonly

Request body

In the request body, supply a Files resource with the following properties as the metadata. For more information, see the document on media upload.

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
mimeType string The MIME type of the file. This is only mutable on update when uploading new content. This field can be left blank, and the mimetype will be determined from the uploaded content's MIME type. 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.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 java.io.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.v2;
using Google.Apis.Drive.v2.Data;

// ...

public class MyClass {

  // ...

  /// <summary>
  /// Update an existing file's metadata and content.
  /// </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="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 newTitle,
      String newDescription, String newMimeType, String newFilename, bool newRevision) {
    try {
      // First retrieve the file from the API.
      File file = service.Files.Get(fileId).Fetch();

      // File's new metadata.
      file.Title = newTitle;
      file.Description = newDescription;
      file.MimeType = newMimeType;

      // File's new content.
      byte[] byteArray = System.IO.File.ReadAllBytes(newFilename);
      System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
// Send the request to the API. FilesResource.UpdateMediaUpload request = service.Files.Update(file, fileId, stream, newMimeType); request.NewRevision = newRevision; request.Upload(); File updatedFile = request.ResponseBody; return updatedFile; } 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 Google_DriveService $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 Google_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(fileId=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(
        fileId=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::V2::File]
#   File if updated, nil otherwise
def update_file(client, title, description, mime_type,
                new_revision?, file_name)
  drive = client.discovered_api('drive', 'v2')
  # Retrieve existing metadata
  result = client.execute(
    :api_method => drive.files.get,
    :parameters => { 'fileIid' => 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 => { 'fileId' => 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

JavaScript

Uses the JavaScript client library

/**
 * Update an existing file's metadata and content.
 *
 * @param {String} fileId ID of the file to update.
 * @param {Object} fileMetadata existing Drive file's metadata.
 * @param {File} fileData File object to read data from.
 * @param {Function} callback Callback function to call when the request is complete.
 */
function updateFile(fileId, fileMetadata, fileData, callback) {
  const boundary = '-------314159265358979323846';
  const delimiter = "\r\n--" + boundary + "\r\n";
  const close_delim = "\r\n--" + boundary + "--";

  var reader = new FileReader();
  reader.readAsBinaryString(fileData);
  reader.onload = function(e) {
    var contentType = fileData.type || 'application/octet-stream';
    // Updating the metadata is optional and you can instead use the value from drive.files.get.
    var base64Data = btoa(reader.result);
    var multipartRequestBody =
        delimiter +
        'Content-Type: application/json\r\n\r\n' +
        JSON.stringify(fileMetadata) +
        delimiter +
        'Content-Type: ' + contentType + '\r\n' +
        'Content-Transfer-Encoding: base64\r\n' +
        '\r\n' +
        base64Data +
        close_delim;

    var request = gapi.client.request({
        'path': '/upload/drive/v2/files/' + fileId,
        'method': 'PUT',
        'params': {'uploadType': 'multipart', 'alt': 'json'},
        'headers': {
          'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
        },
        'body': multipartRequestBody});
    if (!callback) {
      callback = function(file) {
        console.log(file)
      };
    }
    request.execute(callback);
  }
}

Go

Uses the Go client library

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

// UpdateFile fetches and updates a given file with the given fields
func UpdateFile(d *drive.Service, fileId string, title string,
    description string, mimeType string, filename string,
    newRevision bool) (*drive.File, error) {
  f, err := d.Files.Get(fileId).Do()
  if err != nil {
    fmt.Printf("An error occurred: %v\n", err)
    return nil, err
  }
  f.Title = title
  f.Description = description
  f.MimeType = mimeType
  m, err := os.Open(filename)
  if err != nil {
    fmt.Printf("An error occurred: %v\n", err)
    return nil, err
  }
  r, err := d.Files.Update(fileId, f).Media(m).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)updateFileWithService:(GTLServiceDrive *)service
                       fileId:(NSString *)fileId
                     newTitle:(NSString *)newTitle
               newDescription:(NSString *)newDescription
                  newMimeType:(NSString *)newMimeType
                      newData:(NSData *)newData
                isNewRevision:(BOOL)isNewRevision
              completionBlock:(void (^)(GTLDriveFile *, NSError *))completionBlock {
  // First retrieve the file from the API.
  GTLQueryDrive *getQuery = [GTLQueryDrive queryForFilesGetWithFileId:fileId];
  // getQueryTicket can be used to track the status of the request.
  GTLServiceTicket *getQueryTicket =
    [service executeQuery:getQuery
        completionHandler:^(GTLServiceTicket *ticket, GTLDriveFile *file,
                            NSError *error) {
          if (error == nil) {
            // File's new metadata.
            file.title = newTitle;
            file.descriptionProperty = newDescription;
            file.mimeType = newMimeType;

            // File's new content.
            GTLUploadParameters *uploadParameters =
              [GTLUploadParameters uploadParametersWithData:newData
                                                   MIMEType:newMimeType];

            // Send the request to the API.
            GTLQueryDrive *updateQuery =
              [GTLQueryDrive queryForFilesUpdateWithObject:file
                                                    fileId:fileId
                                          uploadParameters:uploadParameters];
            updateQuery.newRevision = isNewRevision;
            // updateQueryTicket can be used to track the status of the request.
            GTLServiceTicket *updateQueryTicket =
              [service executeQuery:updateQuery
                  completionHandler:^(GTLServiceTicket *ticket,
                                      GTLDriveFile *updatedFile,
                                      NSError *error) {
                    if (error == nil) {
                      completionBlock(updatedFile, nil);
                    } else {
                      NSLog(@"An error occurred: %@", error);
                      completionBlock(nil, error);
                    }
                  }];
          } else {
            NSLog(@"An error occurred: %@", error);
            completionBlock(nil, error);
          }
        }];
}

// ...

Try it!

Note: APIs Explorer currently supports metadata requests only.

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.