Google Drive SDK

Files: insert

Requires authorization

Inserts a file, and any settable metadata or blob content sent with the request. See an example.

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

POST https://www.googleapis.com/drive/v1/files

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;
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.setParentsCollection(
          Arrays.asList(new File.ParentsCollection().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.v1;
using Google.Apis.Drive.v1.Data;
using Google.Apis.Requests;
using System.Collections.Generic;
using System.Net;
using System.IO;

// ...

public class MyClass {

  // ...

  /// <summary>
  /// Insert new file metadata.
  /// </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>
  /// <returns>Inserted file metadata, null is returned if an API error occurred.</returns>
  private static File insertMetadata(DriveService service, String title, String description, String parentId, String mimeType) {
    // 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.ParentsCollection = new List<File.ParentsCollectionData>(
          {new File.ParentsCollectionData() {Id = parentId});
    }

    try {
      File file = service.Files.Insert(body).Fetch();

      // 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;
    }
  }

  /// <summary>
  /// Insert new file.
  /// </summary>
  /// <param name="service">Drive API service instance.</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 mimeType, String filename) {
    try {
      HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(
        "https://www.googleapis.com/upload/drive/v1/files/");
      request.Method = "POST";

      Stream memStream = new MemoryStream();
      FileStream stream = new FileStream(filename, 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(mimeType)) {
        request.ContentType = mimeType;
      }
      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

/**
 * Insert new file.
 *
 * @param apiDriveService $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 DriveFile The file that was inserted. NULL is returned if an API error occurred.
 */
function insertFile($service, $title, $description, $parentId, $mimeType, $filename) {
  $file = new DriveFile();
  $file->setTitle($title);
  $file->setDescription($description);
  $file->setMimeType($mimeType);

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

  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['parentsCollection'] = [{'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::V1::File]
#   File if created, nil otherwise
def insert_file(client, title, description, parent_id, mime_type, file_name)
  drive = client.discovered_api('drive', 'v1')
  file = drive.files.insert.request_schema.new({
    'title' => title,
    'description' => description,
    'mimeType' => mime_type
  })
  # Set the parent folder.
  if parent_id
    file.parents_collection = [{'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

Authentication required

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

Signing you in...

Google Developers needs your permission to do that.