Google Drive SDK

Files: insert

Requires authorization

Insert a new file. 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: */*

Note: Apps creating shortcuts with files.insert must specify the MIME type application/vnd.google-apps.drive-sdk.

Apps should specify a file extension in the title property when inserting files with the API. For example, an operation to insert a JPEG file should specify something like "title": "cat.jpg" in the metadata.

Subsequent GET requests include the read-only fileExtension property populated with the extension originally specified in the title property. When a Google Drive user requests to download a file, or when the file is downloaded through the sync client, Drive builds a full filename (with extension) based on the title. In cases where the extension is missing, Google Drive attempts to determine the extension based on the file's MIME type.

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:
    POST https://www.googleapis.com/upload/drive/v2/files
  • Metadata URI, for metadata-only requests:
    POST https://www.googleapis.com/drive/v2/files

Parameters

Parameter name Value Description
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)
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 uploaded file. (Default: false)
timedTextLanguage string The language of the timed text.
timedTextTrackName string The timed text track name.
useContentAsIndexableText boolean Whether to use the content as indexable text. (Default: false)
visibility string The visibility of the new file. This parameter is only relevant when 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 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;
import java.util.Arrays;
// ...

public class MyClass {

  // ...

  /**
   * Insert new file.
   *
   * @param service Drive API service instance.
   * @param title Title of the file to insert, including the extension.
   * @param description Description of the file to insert.
   * @param parentId Optional parent folder's ID.
   * @param mimeType MIME type of the file to insert.
   * @param filename Filename of the file to insert.
   * @return Inserted file metadata if successful, {@code null} otherwise.
   */
  private static File insertFile(Drive service, String title, String description,
      String parentId, String mimeType, String filename) {
    // File's metadata.
    File body = new File();
    body.setTitle(title);
    body.setDescription(description);
    body.setMimeType(mimeType);

    // Set the parent folder.
    if (parentId != null && parentId.length() > 0) {
      body.setParents(
          Arrays.asList(new ParentReference().setId(parentId)));
    }

    // File's content.
    java.io.File fileContent = new java.io.File(filename);
    FileContent mediaContent = new FileContent(mimeType, fileContent);
    try {
      File file = service.files().insert(body, mediaContent).execute();

      // Uncomment the following line to print the File ID.
      // System.out.println("File ID: %s" + file.getId());

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

  // ...
}

.NET

Uses the .NET client library

using Google.Apis.Drive.v2;
using Google.Apis.Drive.v2.Data;
using Google.Apis.Requests;
using System.Collections.Generic;
using System.Net;

// ...

public class MyClass {

  // ...

  /// <summary>
  /// Insert new file.
  /// </summary>
  /// <param name="service">Drive API service instance.</param>
  /// <param name="title">Title of the file to insert, including the extension.</param>
  /// <param name="description">Description of the file to insert.</param>
  /// <param name="parentId">Parent folder's ID.</param>
  /// <param name="mimeType">MIME type of the file to insert.</param>
  /// <param name="filename">Filename of the file to insert.</param>
/// <returns>Inserted file metadata, null is returned if an API error occurred.</returns> private static File insertFile(DriveService service, String title, String description, String parentId, String mimeType, String filename) { // File's metadata. File body = new File(); body.Title = title; body.Description = description; body.MimeType = mimeType; // Set the parent folder. if (!String.IsNullOrEmpty(parentId)) { body.Parents = new List<ParentReference>() {new ParentReference() {Id = parentId}}; } // File's content. byte[] byteArray = System.IO.File.ReadAllBytes(filename); MemoryStream stream = new MemoryStream(byteArray);
try { FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, mimeType); request.Upload(); File file = request.ResponseBody; // 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

/**
 * Insert new file.
 *
 * @param Google_DriveService $service Drive API service instance.
 * @param string $title Title of the file to insert, including the extension.
 * @param string $description Description of the file to insert.
 * @param string $parentId Parent folder's ID.
 * @param string $mimeType MIME type of the file to insert.
 * @param string $filename Filename of the file to insert.
 * @return Google_DriveFile The file that was inserted. NULL is returned if an API error occurred.
 */
function insertFile($service, $title, $description, $parentId, $mimeType, $filename) {
  $file = new Google_DriveFile();
  $file->setTitle($title);
  $file->setDescription($description);
  $file->setMimeType($mimeType);

  // Set the parent folder.
  if ($parentId != null) {
    $parent = new ParentReference();
    $parent->setId($parentId);
    $file->setParents(array($parent));
  }

  try {
    $data = file_get_contents($filename);

    $createdFile = $service->files->insert($file, array(
      'data' => $data,
      'mimeType' => $mimeType,
    ));

    // Uncomment the following line to print the File ID
    // print 'File ID: %s' % $createdFile->getId();

    return $createdFile;
  } 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 insert_file(service, title, description, parent_id, mime_type, filename):
  """Insert new file.

  Args:
    service: Drive API service instance.
    title: Title of the file to insert, including the extension.
    description: Description of the file to insert.
    parent_id: Parent folder's ID.
    mime_type: MIME type of the file to insert.
    filename: Filename of the file to insert.
  Returns:
    Inserted file metadata if successful, None otherwise.
  """
  media_body = MediaFileUpload(filename, mimetype=mime_type, resumable=True)
  body = {
    'title': title,
    'description': description,
    'mimeType': mime_type
  }
  # Set the parent folder.
  if parent_id:
    body['parents'] = [{'id': parent_id}]

  try:
    file = service.files().insert(
        body=body,
        media_body=media_body).execute()

    # Uncomment the following line to print the File ID
    # print 'File ID: %s' % file['id']

    return file
  except errors.HttpError, error:
    print 'An error occured: %s' % error
    return None

Ruby

Uses the Ruby client library

##
# Create a new file
#
# @param [Google::APIClient] client
#   Authorized client instance
# @param [String] title
#   Title of file to insert, including the extension.
# @param [String] description
#   Description of file to insert
# @param [String] parent_id
#   Parent folder's ID.
# @param [String] mime_type
#   MIME type of file to insert
# @param [String] file_name
#   Name of file to upload
# @return [Google::APIClient::Schema::Drive::V2::File]
#   File if created, nil otherwise
def insert_file(client, title, description, parent_id, mime_type, file_name)
  drive = client.discovered_api('drive', 'v2')
  file = drive.files.insert.request_schema.new({
    'title' => title,
    'description' => description,
    'mimeType' => mime_type
  })
  # Set the parent folder.
  if parent_id
    file.parents = [{'id' => parent_id}]
  end
  media = Google::APIClient::UploadIO.new(file_name, mime_type)
  result = client.execute(
    :api_method => drive.files.insert,
    :body_object => file,
    :media => media,
    :parameters => {
      'uploadType' => 'multipart',
      'alt' => 'json'})
  if result.status == 200
    return result.data
  else
    puts "An error occurred: #{result.data['error']['message']}"
    return nil
  end
end

JavaScript

Uses the JavaScript client library

/**
 * Insert new file.
 *
 * @param {File} fileData File object to read data from.
 * @param {Function} callback Function to call when the request is complete.
 */
function insertFile(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';
    var metadata = {
      'title': fileData.fileName,
      'mimeType': contentType
    };

    var base64Data = btoa(reader.result);
    var multipartRequestBody =
        delimiter +
        'Content-Type: application/json\r\n\r\n' +
        JSON.stringify(metadata) +
        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',
        'method': 'POST',
        'params': {'uploadType': 'multipart'},
        '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"
)

// InsertFile creates a new file in Drive from the given file and details
func InsertFile(d *drive.Service, title string, description string,
    parentId string, mimeType string, filename string) (*drive.File, error) {
  m, err := os.Open(filename)
  if err != nil {
    fmt.Printf("An error occurred: %v\n", err)
    return nil, err
  }
  f := &drive.File{Title: title, Description: description, MimeType: mimeType}
  if parentId != "" {
    p := &drive.ParentReference{Id: parentId}
    f.Parents = []*drive.ParentReference{p}
  }
  r, err := d.Files.Insert(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)insertFileWithService:(GTLServiceDrive *)service
                        title:(NSString *)title
                  description:(NSString *)description
                     parentId:(NSString *)parentId
                     mimeType:(NSString *)mimeType
                         data:(NSData *)data
              completionBlock:(void (^)(GTLDriveFile *, NSError *))completionBlock {
  GTLDriveFile *file = [GTLDriveFile object];

  file.title = title;
  file.descriptionProperty = description;
  file.mimeType = mimeType;

  if (parentId != null) {
    file.parents = [NSArray arrayWithObjects: parentId, nil];
  }

  GTLUploadParameters *uploadParameters =
    [GTLUploadParameters uploadParametersWithData:data MIMEType:mimeType];
  GTLQueryDrive *query =
    [GTLQueryDrive queryForFilesInsertWithObject:file
                                uploadParameters:uploadParameters];

  // queryTicket can be used to track the status of the request, more information can
  // be found on https://code.google.com/p/google-api-objectivec-client/wiki/Introduction#Uploading_Files
  GTLServiceTicket *queryTicket =
    [service executeQuery:query
        completionHandler:^(GTLServiceTicket *ticket,
                            GTLDriveFile *insertedFile, NSError *error) {
        if (error == nil) {
          // Uncomment the following line to print the File ID.
          // NSLog(@"File ID: %@", insertedFile.identifier);
          completionBlock(insertedFile, nil);
        } 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.