How to send a video to a Google Drive link

The Drive API lets you upload file data when you create or update a

from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_basic():
    """Insert new file.
    Returns : Id's of the file uploaded

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_metadata = {'name': 'download.jpeg'}
        media = MediaFileUpload('download.jpeg',
                                mimetype='image/jpeg')
        # pylint: disable=maybe-no-member
        file = service.files().create(body=file_metadata, media_body=media,
                                      fields='id').execute()
        print(F'File ID: {file.get("id")}')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.get('id')


if __name__ == '__main__':
    upload_basic()
1. For information about how to create a metadata-only
from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_basic():
    """Insert new file.
    Returns : Id's of the file uploaded

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_metadata = {'name': 'download.jpeg'}
        media = MediaFileUpload('download.jpeg',
                                mimetype='image/jpeg')
        # pylint: disable=maybe-no-member
        file = service.files().create(body=file_metadata, media_body=media,
                                      fields='id').execute()
        print(F'File ID: {file.get("id")}')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.get('id')


if __name__ == '__main__':
    upload_basic()
1, refer to Create files.

Show

There are 3 types of uploads you can perform:

  • Simple upload (

    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_basic():
        """Insert new file.
        Returns : Id's of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {'name': 'download.jpeg'}
            media = MediaFileUpload('download.jpeg',
                                    mimetype='image/jpeg')
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File ID: {file.get("id")}')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_basic()
    3)—Use this upload type to transfer a small media file (5 MB or less) without supplying metadata. To perform a simple upload, refer to Perform a simple upload.

  • Multipart upload (

    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_basic():
        """Insert new file.
        Returns : Id's of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {'name': 'download.jpeg'}
            media = MediaFileUpload('download.jpeg',
                                    mimetype='image/jpeg')
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File ID: {file.get("id")}')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_basic()
    4)—Use this upload type to transfer a small file (5 MB or less) along with metadata that describes the file, in a single request. To perform a multipart upload, refer to Perform a multipart upload.

  • Resumable upload (

    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_basic():
        """Insert new file.
        Returns : Id's of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {'name': 'download.jpeg'}
            media = MediaFileUpload('download.jpeg',
                                    mimetype='image/jpeg')
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File ID: {file.get("id")}')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_basic()
    5)—Use this upload type for large files (greater than 5 MB) and when there's a high chance of network interruption, such as when creating a file from a mobile app. Resumable uploads are also a good choice for most applications because they also work for small files at a minimal cost of one additional HTTP request per upload. To perform a resumable upload, refer to Perform a resumable upload.

The Google API client libraries implement at least one of these types of uploads. Refer to the client library documentation for additional details about how to use each of the types.

Note: In the Drive API documentation, media refers to all available files with MIME types supported for upload to Drive. For a list of supported MIME types, refer to Google Workspace and Drive MIME types.Note: Users can upload any file type to Drive using the Drive UI and Drive attempts to detect and automatically set the MIME type. If the MIME type can't be detected, the MIME type is set to
from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_basic():
    """Insert new file.
    Returns : Id's of the file uploaded

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_metadata = {'name': 'download.jpeg'}
        media = MediaFileUpload('download.jpeg',
                                mimetype='image/jpeg')
        # pylint: disable=maybe-no-member
        file = service.files().create(body=file_metadata, media_body=media,
                                      fields='id').execute()
        print(F'File ID: {file.get("id")}')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.get('id')


if __name__ == '__main__':
    upload_basic()
6.

Use from __future__ import print_function import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError from googleapiclient.http import MediaFileUpload def upload_basic(): """Insert new file. Returns : Id's of the file uploaded Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for the application. """ creds, _ = google.auth.default() try: # create drive api client service = build('drive', 'v3', credentials=creds) file_metadata = {'name': 'download.jpeg'} media = MediaFileUpload('download.jpeg', mimetype='image/jpeg') # pylint: disable=maybe-no-member file = service.files().create(body=file_metadata, media_body=media, fields='id').execute() print(F'File ID: {file.get("id")}') except HttpError as error: print(F'An error occurred: {error}') file = None return file.get('id') if __name__ == '__main__': upload_basic()7 vs. from __future__ import print_function import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError from googleapiclient.http import MediaFileUpload def upload_basic(): """Insert new file. Returns : Id's of the file uploaded Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for the application. """ creds, _ = google.auth.default() try: # create drive api client service = build('drive', 'v3', credentials=creds) file_metadata = {'name': 'download.jpeg'} media = MediaFileUpload('download.jpeg', mimetype='image/jpeg') # pylint: disable=maybe-no-member file = service.files().create(body=file_metadata, media_body=media, fields='id').execute() print(F'File ID: {file.get("id")}') except HttpError as error: print(F'An error occurred: {error}') file = None return file.get('id') if __name__ == '__main__': upload_basic()8

As a refresher, the HTTP verb

from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_basic():
    """Insert new file.
    Returns : Id's of the file uploaded

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_metadata = {'name': 'download.jpeg'}
        media = MediaFileUpload('download.jpeg',
                                mimetype='image/jpeg')
        # pylint: disable=maybe-no-member
        file = service.files().create(body=file_metadata, media_body=media,
                                      fields='id').execute()
        print(F'File ID: {file.get("id")}')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.get('id')


if __name__ == '__main__':
    upload_basic()
7 supports a partial file resource update whereas the HTTP verb
from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_basic():
    """Insert new file.
    Returns : Id's of the file uploaded

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_metadata = {'name': 'download.jpeg'}
        media = MediaFileUpload('download.jpeg',
                                mimetype='image/jpeg')
        # pylint: disable=maybe-no-member
        file = service.files().create(body=file_metadata, media_body=media,
                                      fields='id').execute()
        print(F'File ID: {file.get("id")}')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.get('id')


if __name__ == '__main__':
    upload_basic()
8 supports full resource replacement. Note that
from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_basic():
    """Insert new file.
    Returns : Id's of the file uploaded

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_metadata = {'name': 'download.jpeg'}
        media = MediaFileUpload('download.jpeg',
                                mimetype='image/jpeg')
        # pylint: disable=maybe-no-member
        file = service.files().create(body=file_metadata, media_body=media,
                                      fields='id').execute()
        print(F'File ID: {file.get("id")}')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.get('id')


if __name__ == '__main__':
    upload_basic()
8 can introduce breaking changes when adding a new field to an existing resource.

When uploading a file resource, use the following guidelines:

  • Use the HTTP verb documented on the API reference for the initial request of a resumable upload or for the only request of a simple or multipart upload.
  • Use
    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_basic():
        """Insert new file.
        Returns : Id's of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {'name': 'download.jpeg'}
            media = MediaFileUpload('download.jpeg',
                                    mimetype='image/jpeg')
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File ID: {file.get("id")}')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_basic()
    8 for all subsequent requests for a resumable upload once the request has started. These requests are uploading content no matter the method being called.

Perform a simple upload

To perform a simple upload, use the files.create method with

from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_basic():
    """Insert new file.
    Returns : Id's of the file uploaded

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_metadata = {'name': 'download.jpeg'}
        media = MediaFileUpload('download.jpeg',
                                mimetype='image/jpeg')
        # pylint: disable=maybe-no-member
        file = service.files().create(body=file_metadata, media_body=media,
                                      fields='id').execute()
        print(F'File ID: {file.get("id")}')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.get('id')


if __name__ == '__main__':
    upload_basic()
3.

Note: If you're using the older Drive API v2, use the
/**
 * Insert new file.
 * @return{obj} file Id
 * */
async function uploadBasic() {
  const fs = require('fs');
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});
  const fileMetadata = {
    name: 'photo.jpg',
  };
  const media = {
    mimeType: 'image/jpeg',
    body: fs.createReadStream('files/photo.jpg'),
  };
  try {
    const file = await service.files.create({
      resource: fileMetadata,
      media: media,
      fields: 'id',
    });
    console.log('File Id:', file.data.id);
    return file.data.id;
  } catch (err) {
    // TODO(developer) - Handle error
    throw err;
  }
}
4 method. You can find code samples in GitHub. Learn how to migrate to Drive API v3.

The following shows how to perform a simple upload:

HTTP

  1. Create a

    /**
     * Insert new file.
     * @return{obj} file Id
     * */
    async function uploadBasic() {
      const fs = require('fs');
      const {GoogleAuth} = require('google-auth-library');
      const {google} = require('googleapis');
    
      // Get credentials and build service
      // TODO (developer) - Use appropriate auth mechanism for your app
      const auth = new GoogleAuth({
        scopes: 'https://www.googleapis.com/auth/drive',
      });
      const service = google.drive({version: 'v3', auth});
      const fileMetadata = {
        name: 'photo.jpg',
      };
      const media = {
        mimeType: 'image/jpeg',
        body: fs.createReadStream('files/photo.jpg'),
      };
      try {
        const file = await service.files.create({
          resource: fileMetadata,
          media: media,
          fields: 'id',
        });
        console.log('File Id:', file.data.id);
        return file.data.id;
      } catch (err) {
        // TODO(developer) - Handle error
        throw err;
      }
    }
    5 request to the method's /upload URI with the query parameter of
    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_basic():
        """Insert new file.
        Returns : Id's of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {'name': 'download.jpeg'}
            media = MediaFileUpload('download.jpeg',
                                    mimetype='image/jpeg')
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File ID: {file.get("id")}')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_basic()
    3:

    /**
     * Insert new file.
     * @return{obj} file Id
     * */
    async function uploadBasic() {
      const fs = require('fs');
      const {GoogleAuth} = require('google-auth-library');
      const {google} = require('googleapis');
    
      // Get credentials and build service
      // TODO (developer) - Use appropriate auth mechanism for your app
      const auth = new GoogleAuth({
        scopes: 'https://www.googleapis.com/auth/drive',
      });
      const service = google.drive({version: 'v3', auth});
      const fileMetadata = {
        name: 'photo.jpg',
      };
      const media = {
        mimeType: 'image/jpeg',
        body: fs.createReadStream('files/photo.jpg'),
      };
      try {
        const file = await service.files.create({
          resource: fileMetadata,
          media: media,
          fields: 'id',
        });
        console.log('File Id:', file.data.id);
        return file.data.id;
      } catch (err) {
        // TODO(developer) - Handle error
        throw err;
      }
    }
    7

  2. Add the file's data to the request body.

  3. Add these HTTP headers:

    • /**
       * Insert new file.
       * @return{obj} file Id
       * */
      async function uploadBasic() {
        const fs = require('fs');
        const {GoogleAuth} = require('google-auth-library');
        const {google} = require('googleapis');
      
        // Get credentials and build service
        // TODO (developer) - Use appropriate auth mechanism for your app
        const auth = new GoogleAuth({
          scopes: 'https://www.googleapis.com/auth/drive',
        });
        const service = google.drive({version: 'v3', auth});
        const fileMetadata = {
          name: 'photo.jpg',
        };
        const media = {
          mimeType: 'image/jpeg',
          body: fs.createReadStream('files/photo.jpg'),
        };
        try {
          const file = await service.files.create({
            resource: fileMetadata,
            media: media,
            fields: 'id',
          });
          console.log('File Id:', file.data.id);
          return file.data.id;
        } catch (err) {
          // TODO(developer) - Handle error
          throw err;
        }
      }
      8. Set to the MIME media type of the object being uploaded.
    • /**
       * Insert new file.
       * @return{obj} file Id
       * */
      async function uploadBasic() {
        const fs = require('fs');
        const {GoogleAuth} = require('google-auth-library');
        const {google} = require('googleapis');
      
        // Get credentials and build service
        // TODO (developer) - Use appropriate auth mechanism for your app
        const auth = new GoogleAuth({
          scopes: 'https://www.googleapis.com/auth/drive',
        });
        const service = google.drive({version: 'v3', auth});
        const fileMetadata = {
          name: 'photo.jpg',
        };
        const media = {
          mimeType: 'image/jpeg',
          body: fs.createReadStream('files/photo.jpg'),
        };
        try {
          const file = await service.files.create({
            resource: fileMetadata,
            media: media,
            fields: 'id',
          });
          console.log('File Id:', file.data.id);
          return file.data.id;
        } catch (err) {
          // TODO(developer) - Handle error
          throw err;
        }
      }
      9. Set to the number of bytes you upload. If you use chunked transfer encoding, this header is not required.
  4. Send the request. If the request succeeds, the server returns the

    use Google\Client;
    use Google\Service\Drive;
    # TODO - PHP client currently chokes on fetching start page token
    function uploadBasic()
    {
        try {
            $client = new Client();
            $client->useApplicationDefaultCredentials();
            $client->addScope(Drive::DRIVE);
            $driveService = new Drive($client);
            $fileMetadata = new Drive\DriveFile(array(
            'name' => 'photo.jpg'));
            $content = file_get_contents('../files/photo.jpg');
            $file = $driveService->files->create($fileMetadata, array(
                'data' => $content,
                'mimeType' => 'image/jpeg',
                'uploadType' => 'multipart',
                'fields' => 'id'));
            printf("File ID: %s\n", $file->id);
            return $file->id;
        } catch(Exception $e) {
            echo "Error Message: ".$e;
        } 
    
    }
    0 status code along with the file's metadata. {HTTP}

Note: To update an existing file, use
from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_basic():
    """Insert new file.
    Returns : Id's of the file uploaded

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_metadata = {'name': 'download.jpeg'}
        media = MediaFileUpload('download.jpeg',
                                mimetype='image/jpeg')
        # pylint: disable=maybe-no-member
        file = service.files().create(body=file_metadata, media_body=media,
                                      fields='id').execute()
        print(F'File ID: {file.get("id")}')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.get('id')


if __name__ == '__main__':
    upload_basic()
7.

When you perform a simple upload, basic metadata is created and some attributes are inferred from the file, such as the MIME type or

use Google\Client;
use Google\Service\Drive;
# TODO - PHP client currently chokes on fetching start page token
function uploadBasic()
{
    try {
        $client = new Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope(Drive::DRIVE);
        $driveService = new Drive($client);
        $fileMetadata = new Drive\DriveFile(array(
        'name' => 'photo.jpg'));
        $content = file_get_contents('../files/photo.jpg');
        $file = $driveService->files->create($fileMetadata, array(
            'data' => $content,
            'mimeType' => 'image/jpeg',
            'uploadType' => 'multipart',
            'fields' => 'id'));
        printf("File ID: %s\n", $file->id);
        return $file->id;
    } catch(Exception $e) {
        echo "Error Message: ".$e;
    } 

}
2. You can use a simple upload in cases where you have small files and file metadata isn't important.

Perform a multipart upload

A multipart upload request lets you upload metadata and data in the same request. Use this option if the data you send is small enough to upload again, in its entirety, if the connection fails.

To perform a multipart upload, use the files.create method with

from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_basic():
    """Insert new file.
    Returns : Id's of the file uploaded

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_metadata = {'name': 'download.jpeg'}
        media = MediaFileUpload('download.jpeg',
                                mimetype='image/jpeg')
        # pylint: disable=maybe-no-member
        file = service.files().create(body=file_metadata, media_body=media,
                                      fields='id').execute()
        print(F'File ID: {file.get("id")}')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.get('id')


if __name__ == '__main__':
    upload_basic()
4.

Note: If you're using the older Drive API v2, use the
/**
 * Insert new file.
 * @return{obj} file Id
 * */
async function uploadBasic() {
  const fs = require('fs');
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});
  const fileMetadata = {
    name: 'photo.jpg',
  };
  const media = {
    mimeType: 'image/jpeg',
    body: fs.createReadStream('files/photo.jpg'),
  };
  try {
    const file = await service.files.create({
      resource: fileMetadata,
      media: media,
      fields: 'id',
    });
    console.log('File Id:', file.data.id);
    return file.data.id;
  } catch (err) {
    // TODO(developer) - Handle error
    throw err;
  }
}
4 method. You can find code samples in GitHub. Learn how to migrate to Drive API v3.

The following shows how to perform a multipart upload:

Java

drive/snippets/drive_v3/src/main/java/UploadBasic.java

View on GitHub

import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Arrays;

/* Class to demonstrate use of Drive insert file API */
public class UploadBasic {

  /**
   * Upload new file.
   *
   * @return Inserted file metadata if successful, {@code null} otherwise.
   * @throws IOException if service account credentials file not found.
   */
  public static String uploadBasic() throws IOException {
    // Load pre-authorized user credentials from the environment.
    // TODO(developer) - See https://developers.google.com/identity for
    // guides on implementing OAuth2 for your application.
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
        .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
        credentials);

    // Build a new authorized API client service.
    Drive service = new Drive.Builder(new NetHttpTransport(),
        GsonFactory.getDefaultInstance(),
        requestInitializer)
        .setApplicationName("Drive samples")
        .build();
    // Upload file photo.jpg on drive.
    File fileMetadata = new File();
    fileMetadata.setName("photo.jpg");
    // File's content.
    java.io.File filePath = new java.io.File("files/photo.jpg");
    // Specify media type and file-path for file.
    FileContent mediaContent = new FileContent("image/jpeg", filePath);
    try {
      File file = service.files().create(fileMetadata, mediaContent)
          .setFields("id")
          .execute();
      System.out.println("File ID: " + file.getId());
      return file.getId();
    } catch (GoogleJsonResponseException e) {
      // TODO(developer) - handle error appropriately
      System.err.println("Unable to upload file: " + e.getDetails());
      throw e;
    }
  }
}

Python

drive/snippets/drive-v3/file_snippet/upload_basic.py

View on GitHub

from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_basic():
    """Insert new file.
    Returns : Id's of the file uploaded

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_metadata = {'name': 'download.jpeg'}
        media = MediaFileUpload('download.jpeg',
                                mimetype='image/jpeg')
        # pylint: disable=maybe-no-member
        file = service.files().create(body=file_metadata, media_body=media,
                                      fields='id').execute()
        print(F'File ID: {file.get("id")}')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.get('id')


if __name__ == '__main__':
    upload_basic()

Node.js

drive/snippets/drive_v3/file_snippets/upload_basic.js

View on GitHub

/**
 * Insert new file.
 * @return{obj} file Id
 * */
async function uploadBasic() {
  const fs = require('fs');
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});
  const fileMetadata = {
    name: 'photo.jpg',
  };
  const media = {
    mimeType: 'image/jpeg',
    body: fs.createReadStream('files/photo.jpg'),
  };
  try {
    const file = await service.files.create({
      resource: fileMetadata,
      media: media,
      fields: 'id',
    });
    console.log('File Id:', file.data.id);
    return file.data.id;
  } catch (err) {
    // TODO(developer) - Handle error
    throw err;
  }
}

PHP

drive/snippets/drive_v3/src/DriveUploadBasic.php

View on GitHub

use Google\Client;
use Google\Service\Drive;
# TODO - PHP client currently chokes on fetching start page token
function uploadBasic()
{
    try {
        $client = new Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope(Drive::DRIVE);
        $driveService = new Drive($client);
        $fileMetadata = new Drive\DriveFile(array(
        'name' => 'photo.jpg'));
        $content = file_get_contents('../files/photo.jpg');
        $file = $driveService->files->create($fileMetadata, array(
            'data' => $content,
            'mimeType' => 'image/jpeg',
            'uploadType' => 'multipart',
            'fields' => 'id'));
        printf("File ID: %s\n", $file->id);
        return $file->id;
    } catch(Exception $e) {
        echo "Error Message: ".$e;
    } 

}

.NET

drive/snippets/drive_v3/DriveV3Snippets/UploadBasic.cs

View on GitHub

using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;

namespace DriveV3Snippets
{
    // Class to demonstrate use of Drive insert file API
    public class UploadBasic
    {
        /// 
        /// Upload new file.
        /// 
        /// Image path to upload.
        /// Inserted file metadata if successful, null otherwise.
        public static string DriveUploadBasic(string filePath)
        {
            try
            {
                /* Load pre-authorized user credentials from the environment.
                 TODO(developer) - See https://developers.google.com/identity for
                 guides on implementing OAuth2 for your application. */
                GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                    .CreateScoped(DriveService.Scope.Drive);

                // Create Drive API service.
                var service = new DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Drive API Snippets"
                });

                // Upload file photo.jpg on drive.
                var fileMetadata = new Google.Apis.Drive.v3.Data.File()
                {
                    Name = "photo.jpg"
                };
                FilesResource.CreateMediaUpload request;
                // Create a new file on drive.
                using (var stream = new FileStream(filePath,
                           FileMode.Open))
                {
                    // Create a new file, with metadata and stream.
                    request = service.Files.Create(
                        fileMetadata, stream, "image/jpeg");
                    request.Fields = "id";
                    request.Upload();
                }

                var file = request.ResponseBody;
                // Prints the uploaded file id.
                Console.WriteLine("File ID: " + file.Id);
                return file.Id;
            }
            catch (Exception e)
            {
                // TODO(developer) - handle error appropriately
                if (e is AggregateException)
                {
                    Console.WriteLine("Credential Not found");
                }
                else if (e is FileNotFoundException)
                {
                    Console.WriteLine("File not found");
                }
                else
                {
                    throw;
                }
            }
            return null;
        }
    }
}

HTTP

  1. Create a

    /**
     * Insert new file.
     * @return{obj} file Id
     * */
    async function uploadBasic() {
      const fs = require('fs');
      const {GoogleAuth} = require('google-auth-library');
      const {google} = require('googleapis');
    
      // Get credentials and build service
      // TODO (developer) - Use appropriate auth mechanism for your app
      const auth = new GoogleAuth({
        scopes: 'https://www.googleapis.com/auth/drive',
      });
      const service = google.drive({version: 'v3', auth});
      const fileMetadata = {
        name: 'photo.jpg',
      };
      const media = {
        mimeType: 'image/jpeg',
        body: fs.createReadStream('files/photo.jpg'),
      };
      try {
        const file = await service.files.create({
          resource: fileMetadata,
          media: media,
          fields: 'id',
        });
        console.log('File Id:', file.data.id);
        return file.data.id;
      } catch (err) {
        // TODO(developer) - Handle error
        throw err;
      }
    }
    5 request to the method's /upload URI with the query parameter of
    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_basic():
        """Insert new file.
        Returns : Id's of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {'name': 'download.jpeg'}
            media = MediaFileUpload('download.jpeg',
                                    mimetype='image/jpeg')
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File ID: {file.get("id")}')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_basic()
    4:

    use Google\Client;
    use Google\Service\Drive;
    # TODO - PHP client currently chokes on fetching start page token
    function uploadBasic()
    {
        try {
            $client = new Client();
            $client->useApplicationDefaultCredentials();
            $client->addScope(Drive::DRIVE);
            $driveService = new Drive($client);
            $fileMetadata = new Drive\DriveFile(array(
            'name' => 'photo.jpg'));
            $content = file_get_contents('../files/photo.jpg');
            $file = $driveService->files->create($fileMetadata, array(
                'data' => $content,
                'mimeType' => 'image/jpeg',
                'uploadType' => 'multipart',
                'fields' => 'id'));
            printf("File ID: %s\n", $file->id);
            return $file->id;
        } catch(Exception $e) {
            echo "Error Message: ".$e;
        } 
    
    }
    7

  2. Create the body of the request. Format the body according to the multipart/related content type [RFC 2387], which contains 2 parts:

    • Metadata. The metadata must come first and must have a
      /**
       * Insert new file.
       * @return{obj} file Id
       * */
      async function uploadBasic() {
        const fs = require('fs');
        const {GoogleAuth} = require('google-auth-library');
        const {google} = require('googleapis');
      
        // Get credentials and build service
        // TODO (developer) - Use appropriate auth mechanism for your app
        const auth = new GoogleAuth({
          scopes: 'https://www.googleapis.com/auth/drive',
        });
        const service = google.drive({version: 'v3', auth});
        const fileMetadata = {
          name: 'photo.jpg',
        };
        const media = {
          mimeType: 'image/jpeg',
          body: fs.createReadStream('files/photo.jpg'),
        };
        try {
          const file = await service.files.create({
            resource: fileMetadata,
            media: media,
            fields: 'id',
          });
          console.log('File Id:', file.data.id);
          return file.data.id;
        } catch (err) {
          // TODO(developer) - Handle error
          throw err;
        }
      }
      8 header set to
      use Google\Client;
      use Google\Service\Drive;
      # TODO - PHP client currently chokes on fetching start page token
      function uploadBasic()
      {
          try {
              $client = new Client();
              $client->useApplicationDefaultCredentials();
              $client->addScope(Drive::DRIVE);
              $driveService = new Drive($client);
              $fileMetadata = new Drive\DriveFile(array(
              'name' => 'photo.jpg'));
              $content = file_get_contents('../files/photo.jpg');
              $file = $driveService->files->create($fileMetadata, array(
                  'data' => $content,
                  'mimeType' => 'image/jpeg',
                  'uploadType' => 'multipart',
                  'fields' => 'id'));
              printf("File ID: %s\n", $file->id);
              return $file->id;
          } catch(Exception $e) {
              echo "Error Message: ".$e;
          } 
      
      }
      9
      using Google.Apis.Auth.OAuth2;
      using Google.Apis.Drive.v3;
      using Google.Apis.Services;
      
      namespace DriveV3Snippets
      {
          // Class to demonstrate use of Drive insert file API
          public class UploadBasic
          {
              /// 
              /// Upload new file.
              /// 
              /// Image path to upload.
              /// Inserted file metadata if successful, null otherwise.
              public static string DriveUploadBasic(string filePath)
              {
                  try
                  {
                      /* Load pre-authorized user credentials from the environment.
                       TODO(developer) - See https://developers.google.com/identity for
                       guides on implementing OAuth2 for your application. */
                      GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                          .CreateScoped(DriveService.Scope.Drive);
      
                      // Create Drive API service.
                      var service = new DriveService(new BaseClientService.Initializer
                      {
                          HttpClientInitializer = credential,
                          ApplicationName = "Drive API Snippets"
                      });
      
                      // Upload file photo.jpg on drive.
                      var fileMetadata = new Google.Apis.Drive.v3.Data.File()
                      {
                          Name = "photo.jpg"
                      };
                      FilesResource.CreateMediaUpload request;
                      // Create a new file on drive.
                      using (var stream = new FileStream(filePath,
                                 FileMode.Open))
                      {
                          // Create a new file, with metadata and stream.
                          request = service.Files.Create(
                              fileMetadata, stream, "image/jpeg");
                          request.Fields = "id";
                          request.Upload();
                      }
      
                      var file = request.ResponseBody;
                      // Prints the uploaded file id.
                      Console.WriteLine("File ID: " + file.Id);
                      return file.Id;
                  }
                  catch (Exception e)
                  {
                      // TODO(developer) - handle error appropriately
                      if (e is AggregateException)
                      {
                          Console.WriteLine("Credential Not found");
                      }
                      else if (e is FileNotFoundException)
                      {
                          Console.WriteLine("File not found");
                      }
                      else
                      {
                          throw;
                      }
                  }
                  return null;
              }
          }
      }
      0. Add the file's metadata in JSON format.
    • Media. The media must come second and must have a
      /**
       * Insert new file.
       * @return{obj} file Id
       * */
      async function uploadBasic() {
        const fs = require('fs');
        const {GoogleAuth} = require('google-auth-library');
        const {google} = require('googleapis');
      
        // Get credentials and build service
        // TODO (developer) - Use appropriate auth mechanism for your app
        const auth = new GoogleAuth({
          scopes: 'https://www.googleapis.com/auth/drive',
        });
        const service = google.drive({version: 'v3', auth});
        const fileMetadata = {
          name: 'photo.jpg',
        };
        const media = {
          mimeType: 'image/jpeg',
          body: fs.createReadStream('files/photo.jpg'),
        };
        try {
          const file = await service.files.create({
            resource: fileMetadata,
            media: media,
            fields: 'id',
          });
          console.log('File Id:', file.data.id);
          return file.data.id;
        } catch (err) {
          // TODO(developer) - Handle error
          throw err;
        }
      }
      8 header of any MIME type. Add the file's data to the media part.

    Identify each part with a boundary string, preceded by 2 hyphens. In addition, add 2 hyphens after the final boundary string.

  3. Add these top-level HTTP headers:

    • /**
       * Insert new file.
       * @return{obj} file Id
       * */
      async function uploadBasic() {
        const fs = require('fs');
        const {GoogleAuth} = require('google-auth-library');
        const {google} = require('googleapis');
      
        // Get credentials and build service
        // TODO (developer) - Use appropriate auth mechanism for your app
        const auth = new GoogleAuth({
          scopes: 'https://www.googleapis.com/auth/drive',
        });
        const service = google.drive({version: 'v3', auth});
        const fileMetadata = {
          name: 'photo.jpg',
        };
        const media = {
          mimeType: 'image/jpeg',
          body: fs.createReadStream('files/photo.jpg'),
        };
        try {
          const file = await service.files.create({
            resource: fileMetadata,
            media: media,
            fields: 'id',
          });
          console.log('File Id:', file.data.id);
          return file.data.id;
        } catch (err) {
          // TODO(developer) - Handle error
          throw err;
        }
      }
      8. Set to
      using Google.Apis.Auth.OAuth2;
      using Google.Apis.Drive.v3;
      using Google.Apis.Services;
      
      namespace DriveV3Snippets
      {
          // Class to demonstrate use of Drive insert file API
          public class UploadBasic
          {
              /// 
              /// Upload new file.
              /// 
              /// Image path to upload.
              /// Inserted file metadata if successful, null otherwise.
              public static string DriveUploadBasic(string filePath)
              {
                  try
                  {
                      /* Load pre-authorized user credentials from the environment.
                       TODO(developer) - See https://developers.google.com/identity for
                       guides on implementing OAuth2 for your application. */
                      GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                          .CreateScoped(DriveService.Scope.Drive);
      
                      // Create Drive API service.
                      var service = new DriveService(new BaseClientService.Initializer
                      {
                          HttpClientInitializer = credential,
                          ApplicationName = "Drive API Snippets"
                      });
      
                      // Upload file photo.jpg on drive.
                      var fileMetadata = new Google.Apis.Drive.v3.Data.File()
                      {
                          Name = "photo.jpg"
                      };
                      FilesResource.CreateMediaUpload request;
                      // Create a new file on drive.
                      using (var stream = new FileStream(filePath,
                                 FileMode.Open))
                      {
                          // Create a new file, with metadata and stream.
                          request = service.Files.Create(
                              fileMetadata, stream, "image/jpeg");
                          request.Fields = "id";
                          request.Upload();
                      }
      
                      var file = request.ResponseBody;
                      // Prints the uploaded file id.
                      Console.WriteLine("File ID: " + file.Id);
                      return file.Id;
                  }
                  catch (Exception e)
                  {
                      // TODO(developer) - handle error appropriately
                      if (e is AggregateException)
                      {
                          Console.WriteLine("Credential Not found");
                      }
                      else if (e is FileNotFoundException)
                      {
                          Console.WriteLine("File not found");
                      }
                      else
                      {
                          throw;
                      }
                  }
                  return null;
              }
          }
      }
      3 and include the boundary string you're using to identify the different parts of the request. For example:
      using Google.Apis.Auth.OAuth2;
      using Google.Apis.Drive.v3;
      using Google.Apis.Services;
      
      namespace DriveV3Snippets
      {
          // Class to demonstrate use of Drive insert file API
          public class UploadBasic
          {
              /// 
              /// Upload new file.
              /// 
              /// Image path to upload.
              /// Inserted file metadata if successful, null otherwise.
              public static string DriveUploadBasic(string filePath)
              {
                  try
                  {
                      /* Load pre-authorized user credentials from the environment.
                       TODO(developer) - See https://developers.google.com/identity for
                       guides on implementing OAuth2 for your application. */
                      GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                          .CreateScoped(DriveService.Scope.Drive);
      
                      // Create Drive API service.
                      var service = new DriveService(new BaseClientService.Initializer
                      {
                          HttpClientInitializer = credential,
                          ApplicationName = "Drive API Snippets"
                      });
      
                      // Upload file photo.jpg on drive.
                      var fileMetadata = new Google.Apis.Drive.v3.Data.File()
                      {
                          Name = "photo.jpg"
                      };
                      FilesResource.CreateMediaUpload request;
                      // Create a new file on drive.
                      using (var stream = new FileStream(filePath,
                                 FileMode.Open))
                      {
                          // Create a new file, with metadata and stream.
                          request = service.Files.Create(
                              fileMetadata, stream, "image/jpeg");
                          request.Fields = "id";
                          request.Upload();
                      }
      
                      var file = request.ResponseBody;
                      // Prints the uploaded file id.
                      Console.WriteLine("File ID: " + file.Id);
                      return file.Id;
                  }
                  catch (Exception e)
                  {
                      // TODO(developer) - handle error appropriately
                      if (e is AggregateException)
                      {
                          Console.WriteLine("Credential Not found");
                      }
                      else if (e is FileNotFoundException)
                      {
                          Console.WriteLine("File not found");
                      }
                      else
                      {
                          throw;
                      }
                  }
                  return null;
              }
          }
      }
      4
    • /**
       * Insert new file.
       * @return{obj} file Id
       * */
      async function uploadBasic() {
        const fs = require('fs');
        const {GoogleAuth} = require('google-auth-library');
        const {google} = require('googleapis');
      
        // Get credentials and build service
        // TODO (developer) - Use appropriate auth mechanism for your app
        const auth = new GoogleAuth({
          scopes: 'https://www.googleapis.com/auth/drive',
        });
        const service = google.drive({version: 'v3', auth});
        const fileMetadata = {
          name: 'photo.jpg',
        };
        const media = {
          mimeType: 'image/jpeg',
          body: fs.createReadStream('files/photo.jpg'),
        };
        try {
          const file = await service.files.create({
            resource: fileMetadata,
            media: media,
            fields: 'id',
          });
          console.log('File Id:', file.data.id);
          return file.data.id;
        } catch (err) {
          // TODO(developer) - Handle error
          throw err;
        }
      }
      9. Set to the total number of bytes in the request body.
  4. Send the request.

To create or update the metadata portion only, without the associated data, send a

/**
 * Insert new file.
 * @return{obj} file Id
 * */
async function uploadBasic() {
  const fs = require('fs');
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});
  const fileMetadata = {
    name: 'photo.jpg',
  };
  const media = {
    mimeType: 'image/jpeg',
    body: fs.createReadStream('files/photo.jpg'),
  };
  try {
    const file = await service.files.create({
      resource: fileMetadata,
      media: media,
      fields: 'id',
    });
    console.log('File Id:', file.data.id);
    return file.data.id;
  } catch (err) {
    // TODO(developer) - Handle error
    throw err;
  }
}
5 or
from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_basic():
    """Insert new file.
    Returns : Id's of the file uploaded

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_metadata = {'name': 'download.jpeg'}
        media = MediaFileUpload('download.jpeg',
                                mimetype='image/jpeg')
        # pylint: disable=maybe-no-member
        file = service.files().create(body=file_metadata, media_body=media,
                                      fields='id').execute()
        print(F'File ID: {file.get("id")}')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.get('id')


if __name__ == '__main__':
    upload_basic()
7 request to the standard resource endpoint:
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;

namespace DriveV3Snippets
{
    // Class to demonstrate use of Drive insert file API
    public class UploadBasic
    {
        /// 
        /// Upload new file.
        /// 
        /// Image path to upload.
        /// Inserted file metadata if successful, null otherwise.
        public static string DriveUploadBasic(string filePath)
        {
            try
            {
                /* Load pre-authorized user credentials from the environment.
                 TODO(developer) - See https://developers.google.com/identity for
                 guides on implementing OAuth2 for your application. */
                GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                    .CreateScoped(DriveService.Scope.Drive);

                // Create Drive API service.
                var service = new DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Drive API Snippets"
                });

                // Upload file photo.jpg on drive.
                var fileMetadata = new Google.Apis.Drive.v3.Data.File()
                {
                    Name = "photo.jpg"
                };
                FilesResource.CreateMediaUpload request;
                // Create a new file on drive.
                using (var stream = new FileStream(filePath,
                           FileMode.Open))
                {
                    // Create a new file, with metadata and stream.
                    request = service.Files.Create(
                        fileMetadata, stream, "image/jpeg");
                    request.Fields = "id";
                    request.Upload();
                }

                var file = request.ResponseBody;
                // Prints the uploaded file id.
                Console.WriteLine("File ID: " + file.Id);
                return file.Id;
            }
            catch (Exception e)
            {
                // TODO(developer) - handle error appropriately
                if (e is AggregateException)
                {
                    Console.WriteLine("Credential Not found");
                }
                else if (e is FileNotFoundException)
                {
                    Console.WriteLine("File not found");
                }
                else
                {
                    throw;
                }
            }
            return null;
        }
    }
}
8 If the request succeeds, the server returns the
use Google\Client;
use Google\Service\Drive;
# TODO - PHP client currently chokes on fetching start page token
function uploadBasic()
{
    try {
        $client = new Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope(Drive::DRIVE);
        $driveService = new Drive($client);
        $fileMetadata = new Drive\DriveFile(array(
        'name' => 'photo.jpg'));
        $content = file_get_contents('../files/photo.jpg');
        $file = $driveService->files->create($fileMetadata, array(
            'data' => $content,
            'mimeType' => 'image/jpeg',
            'uploadType' => 'multipart',
            'fields' => 'id'));
        printf("File ID: %s\n", $file->id);
        return $file->id;
    } catch(Exception $e) {
        echo "Error Message: ".$e;
    } 

}
0 status code along with the file's metadata.

Note: To update an existing file, use
from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_basic():
    """Insert new file.
    Returns : Id's of the file uploaded

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_metadata = {'name': 'download.jpeg'}
        media = MediaFileUpload('download.jpeg',
                                mimetype='image/jpeg')
        # pylint: disable=maybe-no-member
        file = service.files().create(body=file_metadata, media_body=media,
                                      fields='id').execute()
        print(F'File ID: {file.get("id")}')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.get('id')


if __name__ == '__main__':
    upload_basic()
7.

When creating files, they should specify a file extension in the file's

HTTP/1.1 200 OK
Location: https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&upload_id=xa298sd_sdlkj2
Content-Length: 0
1 field. For example, when creating a photo JPEG file, you might specify something like
HTTP/1.1 200 OK
Location: https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&upload_id=xa298sd_sdlkj2
Content-Length: 0
2 in the metadata. Subsequent calls to files.get return the read-only
HTTP/1.1 200 OK
Location: https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&upload_id=xa298sd_sdlkj2
Content-Length: 0
3 property containing the extension originally specified in the
HTTP/1.1 200 OK
Location: https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&upload_id=xa298sd_sdlkj2
Content-Length: 0
1 field.

Perform a resumable upload

A resumable upload lets you resume an upload operation after a communication failure interrupts the flow of data. Because you don't have to restart large file uploads from the start, resumable uploads can also reduce your bandwidth usage if there's a network failure.

Resumable uploads are useful when your file sizes might vary greatly or when there's a fixed time limit for requests (such as mobile OS background tasks and certain App Engine requests). You might also use resumable uploads for situations where you want to show an upload progress bar.

A resumable upload consists of several high-level steps:

  1. Send the initial request and retrieve the resumable session URI.
  2. Upload the data and monitor upload state.
  3. (optional) If the upload is disturbed, resume the upload.

Send the initial request

To initiate a resumable upload, use the files.create method with

from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_basic():
    """Insert new file.
    Returns : Id's of the file uploaded

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_metadata = {'name': 'download.jpeg'}
        media = MediaFileUpload('download.jpeg',
                                mimetype='image/jpeg')
        # pylint: disable=maybe-no-member
        file = service.files().create(body=file_metadata, media_body=media,
                                      fields='id').execute()
        print(F'File ID: {file.get("id")}')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.get('id')


if __name__ == '__main__':
    upload_basic()
5.

Note: If you're using the older Drive API v2, use the
/**
 * Insert new file.
 * @return{obj} file Id
 * */
async function uploadBasic() {
  const fs = require('fs');
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});
  const fileMetadata = {
    name: 'photo.jpg',
  };
  const media = {
    mimeType: 'image/jpeg',
    body: fs.createReadStream('files/photo.jpg'),
  };
  try {
    const file = await service.files.create({
      resource: fileMetadata,
      media: media,
      fields: 'id',
    });
    console.log('File Id:', file.data.id);
    return file.data.id;
  } catch (err) {
    // TODO(developer) - Handle error
    throw err;
  }
}
4 method. You can find code samples in GitHub. Learn how to migrate to Drive API v3.

HTTP

  1. Create a

    /**
     * Insert new file.
     * @return{obj} file Id
     * */
    async function uploadBasic() {
      const fs = require('fs');
      const {GoogleAuth} = require('google-auth-library');
      const {google} = require('googleapis');
    
      // Get credentials and build service
      // TODO (developer) - Use appropriate auth mechanism for your app
      const auth = new GoogleAuth({
        scopes: 'https://www.googleapis.com/auth/drive',
      });
      const service = google.drive({version: 'v3', auth});
      const fileMetadata = {
        name: 'photo.jpg',
      };
      const media = {
        mimeType: 'image/jpeg',
        body: fs.createReadStream('files/photo.jpg'),
      };
      try {
        const file = await service.files.create({
          resource: fileMetadata,
          media: media,
          fields: 'id',
        });
        console.log('File Id:', file.data.id);
        return file.data.id;
      } catch (err) {
        // TODO(developer) - Handle error
        throw err;
      }
    }
    5 request to the method's /upload URI with the query parameter of
    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_basic():
        """Insert new file.
        Returns : Id's of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {'name': 'download.jpeg'}
            media = MediaFileUpload('download.jpeg',
                                    mimetype='image/jpeg')
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File ID: {file.get("id")}')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_basic()
    5:

    HTTP/1.1 200 OK
    Location: https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&upload_id=xa298sd_sdlkj2
    Content-Length: 0
    
    9

    If the initiation request succeeds, the response includes a

    import com.google.api.client.googleapis.json.GoogleJsonResponseException;
    import com.google.api.client.http.FileContent;
    import com.google.api.client.http.HttpRequestInitializer;
    import com.google.api.client.http.javanet.NetHttpTransport;
    import com.google.api.client.json.gson.GsonFactory;
    import com.google.api.services.drive.Drive;
    import com.google.api.services.drive.DriveScopes;
    import com.google.api.services.drive.model.File;
    import com.google.auth.http.HttpCredentialsAdapter;
    import com.google.auth.oauth2.GoogleCredentials;
    import java.io.IOException;
    import java.util.Arrays;
    
    /* Class to demonstrate Drive's upload with conversion use-case. */
    public class UploadWithConversion {
    
      /**
       * Upload file with conversion.
       *
       * @return Inserted file id if successful, {@code null} otherwise.
       * @throws IOException if service account credentials file not found.
       */
      public static String uploadWithConversion() throws IOException {
        // Load pre-authorized user credentials from the environment.
        // TODO(developer) - See https://developers.google.com/identity for
        // guides on implementing OAuth2 for your application.
        GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
            .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));
        HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
            credentials);
    
        // Build a new authorized API client service.
        Drive service = new Drive.Builder(new NetHttpTransport(),
            GsonFactory.getDefaultInstance(),
            requestInitializer)
            .setApplicationName("Drive samples")
            .build();
    
        // File's metadata.
        File fileMetadata = new File();
        fileMetadata.setName("My Report");
        fileMetadata.setMimeType("application/vnd.google-apps.spreadsheet");
    
        java.io.File filePath = new java.io.File("files/report.csv");
        FileContent mediaContent = new FileContent("text/csv", filePath);
        try {
          File file = service.files().create(fileMetadata, mediaContent)
              .setFields("id")
              .execute();
          System.out.println("File ID: " + file.getId());
          return file.getId();
        } catch (GoogleJsonResponseException e) {
          // TODO(developer) - handle error appropriately
          System.err.println("Unable to move file: " + e.getDetails());
          throw e;
        }
      }
    }
    0 HTTP status code. In addition, it includes a
    import com.google.api.client.googleapis.json.GoogleJsonResponseException;
    import com.google.api.client.http.FileContent;
    import com.google.api.client.http.HttpRequestInitializer;
    import com.google.api.client.http.javanet.NetHttpTransport;
    import com.google.api.client.json.gson.GsonFactory;
    import com.google.api.services.drive.Drive;
    import com.google.api.services.drive.DriveScopes;
    import com.google.api.services.drive.model.File;
    import com.google.auth.http.HttpCredentialsAdapter;
    import com.google.auth.oauth2.GoogleCredentials;
    import java.io.IOException;
    import java.util.Arrays;
    
    /* Class to demonstrate Drive's upload with conversion use-case. */
    public class UploadWithConversion {
    
      /**
       * Upload file with conversion.
       *
       * @return Inserted file id if successful, {@code null} otherwise.
       * @throws IOException if service account credentials file not found.
       */
      public static String uploadWithConversion() throws IOException {
        // Load pre-authorized user credentials from the environment.
        // TODO(developer) - See https://developers.google.com/identity for
        // guides on implementing OAuth2 for your application.
        GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
            .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));
        HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
            credentials);
    
        // Build a new authorized API client service.
        Drive service = new Drive.Builder(new NetHttpTransport(),
            GsonFactory.getDefaultInstance(),
            requestInitializer)
            .setApplicationName("Drive samples")
            .build();
    
        // File's metadata.
        File fileMetadata = new File();
        fileMetadata.setName("My Report");
        fileMetadata.setMimeType("application/vnd.google-apps.spreadsheet");
    
        java.io.File filePath = new java.io.File("files/report.csv");
        FileContent mediaContent = new FileContent("text/csv", filePath);
        try {
          File file = service.files().create(fileMetadata, mediaContent)
              .setFields("id")
              .execute();
          System.out.println("File ID: " + file.getId());
          return file.getId();
        } catch (GoogleJsonResponseException e) {
          // TODO(developer) - handle error appropriately
          System.err.println("Unable to move file: " + e.getDetails());
          throw e;
        }
      }
    }
    1 header that specifies the resumable session URI:

    HTTP/1.1 200 OK
    Location: https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&upload_id=xa298sd_sdlkj2
    Content-Length: 0
    

    Save the resumable session URI so you can upload the file data and query the upload status. A resumable session URI expires after one week.

    Note: To update an existing file, use
    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_basic():
        """Insert new file.
        Returns : Id's of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {'name': 'download.jpeg'}
            media = MediaFileUpload('download.jpeg',
                                    mimetype='image/jpeg')
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File ID: {file.get("id")}')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_basic()
    8.
  2. If you have metadata for the file, add the metadata to the request body in JSON format. Otherwise, leave the request body empty.

  3. Add these HTTP headers:

    • import com.google.api.client.googleapis.json.GoogleJsonResponseException;
      import com.google.api.client.http.FileContent;
      import com.google.api.client.http.HttpRequestInitializer;
      import com.google.api.client.http.javanet.NetHttpTransport;
      import com.google.api.client.json.gson.GsonFactory;
      import com.google.api.services.drive.Drive;
      import com.google.api.services.drive.DriveScopes;
      import com.google.api.services.drive.model.File;
      import com.google.auth.http.HttpCredentialsAdapter;
      import com.google.auth.oauth2.GoogleCredentials;
      import java.io.IOException;
      import java.util.Arrays;
      
      /* Class to demonstrate Drive's upload with conversion use-case. */
      public class UploadWithConversion {
      
        /**
         * Upload file with conversion.
         *
         * @return Inserted file id if successful, {@code null} otherwise.
         * @throws IOException if service account credentials file not found.
         */
        public static String uploadWithConversion() throws IOException {
          // Load pre-authorized user credentials from the environment.
          // TODO(developer) - See https://developers.google.com/identity for
          // guides on implementing OAuth2 for your application.
          GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
              .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));
          HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
              credentials);
      
          // Build a new authorized API client service.
          Drive service = new Drive.Builder(new NetHttpTransport(),
              GsonFactory.getDefaultInstance(),
              requestInitializer)
              .setApplicationName("Drive samples")
              .build();
      
          // File's metadata.
          File fileMetadata = new File();
          fileMetadata.setName("My Report");
          fileMetadata.setMimeType("application/vnd.google-apps.spreadsheet");
      
          java.io.File filePath = new java.io.File("files/report.csv");
          FileContent mediaContent = new FileContent("text/csv", filePath);
          try {
            File file = service.files().create(fileMetadata, mediaContent)
                .setFields("id")
                .execute();
            System.out.println("File ID: " + file.getId());
            return file.getId();
          } catch (GoogleJsonResponseException e) {
            // TODO(developer) - handle error appropriately
            System.err.println("Unable to move file: " + e.getDetails());
            throw e;
          }
        }
      }
      3. Optional. Set to the MIME type of the file data, which is transferred in subsequent requests. If the MIME type of the data is not specified in the metadata or through this header, the object is served as
      import com.google.api.client.googleapis.json.GoogleJsonResponseException;
      import com.google.api.client.http.FileContent;
      import com.google.api.client.http.HttpRequestInitializer;
      import com.google.api.client.http.javanet.NetHttpTransport;
      import com.google.api.client.json.gson.GsonFactory;
      import com.google.api.services.drive.Drive;
      import com.google.api.services.drive.DriveScopes;
      import com.google.api.services.drive.model.File;
      import com.google.auth.http.HttpCredentialsAdapter;
      import com.google.auth.oauth2.GoogleCredentials;
      import java.io.IOException;
      import java.util.Arrays;
      
      /* Class to demonstrate Drive's upload with conversion use-case. */
      public class UploadWithConversion {
      
        /**
         * Upload file with conversion.
         *
         * @return Inserted file id if successful, {@code null} otherwise.
         * @throws IOException if service account credentials file not found.
         */
        public static String uploadWithConversion() throws IOException {
          // Load pre-authorized user credentials from the environment.
          // TODO(developer) - See https://developers.google.com/identity for
          // guides on implementing OAuth2 for your application.
          GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
              .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));
          HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
              credentials);
      
          // Build a new authorized API client service.
          Drive service = new Drive.Builder(new NetHttpTransport(),
              GsonFactory.getDefaultInstance(),
              requestInitializer)
              .setApplicationName("Drive samples")
              .build();
      
          // File's metadata.
          File fileMetadata = new File();
          fileMetadata.setName("My Report");
          fileMetadata.setMimeType("application/vnd.google-apps.spreadsheet");
      
          java.io.File filePath = new java.io.File("files/report.csv");
          FileContent mediaContent = new FileContent("text/csv", filePath);
          try {
            File file = service.files().create(fileMetadata, mediaContent)
                .setFields("id")
                .execute();
            System.out.println("File ID: " + file.getId());
            return file.getId();
          } catch (GoogleJsonResponseException e) {
            // TODO(developer) - handle error appropriately
            System.err.println("Unable to move file: " + e.getDetails());
            throw e;
          }
        }
      }
      4
    • import com.google.api.client.googleapis.json.GoogleJsonResponseException;
      import com.google.api.client.http.FileContent;
      import com.google.api.client.http.HttpRequestInitializer;
      import com.google.api.client.http.javanet.NetHttpTransport;
      import com.google.api.client.json.gson.GsonFactory;
      import com.google.api.services.drive.Drive;
      import com.google.api.services.drive.DriveScopes;
      import com.google.api.services.drive.model.File;
      import com.google.auth.http.HttpCredentialsAdapter;
      import com.google.auth.oauth2.GoogleCredentials;
      import java.io.IOException;
      import java.util.Arrays;
      
      /* Class to demonstrate Drive's upload with conversion use-case. */
      public class UploadWithConversion {
      
        /**
         * Upload file with conversion.
         *
         * @return Inserted file id if successful, {@code null} otherwise.
         * @throws IOException if service account credentials file not found.
         */
        public static String uploadWithConversion() throws IOException {
          // Load pre-authorized user credentials from the environment.
          // TODO(developer) - See https://developers.google.com/identity for
          // guides on implementing OAuth2 for your application.
          GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
              .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));
          HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
              credentials);
      
          // Build a new authorized API client service.
          Drive service = new Drive.Builder(new NetHttpTransport(),
              GsonFactory.getDefaultInstance(),
              requestInitializer)
              .setApplicationName("Drive samples")
              .build();
      
          // File's metadata.
          File fileMetadata = new File();
          fileMetadata.setName("My Report");
          fileMetadata.setMimeType("application/vnd.google-apps.spreadsheet");
      
          java.io.File filePath = new java.io.File("files/report.csv");
          FileContent mediaContent = new FileContent("text/csv", filePath);
          try {
            File file = service.files().create(fileMetadata, mediaContent)
                .setFields("id")
                .execute();
            System.out.println("File ID: " + file.getId());
            return file.getId();
          } catch (GoogleJsonResponseException e) {
            // TODO(developer) - handle error appropriately
            System.err.println("Unable to move file: " + e.getDetails());
            throw e;
          }
        }
      }
      5. Optional. Set to the number of bytes of file data, which is transferred in subsequent requests.
    • /**
       * Insert new file.
       * @return{obj} file Id
       * */
      async function uploadBasic() {
        const fs = require('fs');
        const {GoogleAuth} = require('google-auth-library');
        const {google} = require('googleapis');
      
        // Get credentials and build service
        // TODO (developer) - Use appropriate auth mechanism for your app
        const auth = new GoogleAuth({
          scopes: 'https://www.googleapis.com/auth/drive',
        });
        const service = google.drive({version: 'v3', auth});
        const fileMetadata = {
          name: 'photo.jpg',
        };
        const media = {
          mimeType: 'image/jpeg',
          body: fs.createReadStream('files/photo.jpg'),
        };
        try {
          const file = await service.files.create({
            resource: fileMetadata,
            media: media,
            fields: 'id',
          });
          console.log('File Id:', file.data.id);
          return file.data.id;
        } catch (err) {
          // TODO(developer) - Handle error
          throw err;
        }
      }
      8. Required if you have metadata for the file. Set to
      use Google\Client;
      use Google\Service\Drive;
      # TODO - PHP client currently chokes on fetching start page token
      function uploadBasic()
      {
          try {
              $client = new Client();
              $client->useApplicationDefaultCredentials();
              $client->addScope(Drive::DRIVE);
              $driveService = new Drive($client);
              $fileMetadata = new Drive\DriveFile(array(
              'name' => 'photo.jpg'));
              $content = file_get_contents('../files/photo.jpg');
              $file = $driveService->files->create($fileMetadata, array(
                  'data' => $content,
                  'mimeType' => 'image/jpeg',
                  'uploadType' => 'multipart',
                  'fields' => 'id'));
              printf("File ID: %s\n", $file->id);
              return $file->id;
          } catch(Exception $e) {
              echo "Error Message: ".$e;
          } 
      
      }
      9
      using Google.Apis.Auth.OAuth2;
      using Google.Apis.Drive.v3;
      using Google.Apis.Services;
      
      namespace DriveV3Snippets
      {
          // Class to demonstrate use of Drive insert file API
          public class UploadBasic
          {
              /// 
              /// Upload new file.
              /// 
              /// Image path to upload.
              /// Inserted file metadata if successful, null otherwise.
              public static string DriveUploadBasic(string filePath)
              {
                  try
                  {
                      /* Load pre-authorized user credentials from the environment.
                       TODO(developer) - See https://developers.google.com/identity for
                       guides on implementing OAuth2 for your application. */
                      GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                          .CreateScoped(DriveService.Scope.Drive);
      
                      // Create Drive API service.
                      var service = new DriveService(new BaseClientService.Initializer
                      {
                          HttpClientInitializer = credential,
                          ApplicationName = "Drive API Snippets"
                      });
      
                      // Upload file photo.jpg on drive.
                      var fileMetadata = new Google.Apis.Drive.v3.Data.File()
                      {
                          Name = "photo.jpg"
                      };
                      FilesResource.CreateMediaUpload request;
                      // Create a new file on drive.
                      using (var stream = new FileStream(filePath,
                                 FileMode.Open))
                      {
                          // Create a new file, with metadata and stream.
                          request = service.Files.Create(
                              fileMetadata, stream, "image/jpeg");
                          request.Fields = "id";
                          request.Upload();
                      }
      
                      var file = request.ResponseBody;
                      // Prints the uploaded file id.
                      Console.WriteLine("File ID: " + file.Id);
                      return file.Id;
                  }
                  catch (Exception e)
                  {
                      // TODO(developer) - handle error appropriately
                      if (e is AggregateException)
                      {
                          Console.WriteLine("Credential Not found");
                      }
                      else if (e is FileNotFoundException)
                      {
                          Console.WriteLine("File not found");
                      }
                      else
                      {
                          throw;
                      }
                  }
                  return null;
              }
          }
      }
      0.
    • /**
       * Insert new file.
       * @return{obj} file Id
       * */
      async function uploadBasic() {
        const fs = require('fs');
        const {GoogleAuth} = require('google-auth-library');
        const {google} = require('googleapis');
      
        // Get credentials and build service
        // TODO (developer) - Use appropriate auth mechanism for your app
        const auth = new GoogleAuth({
          scopes: 'https://www.googleapis.com/auth/drive',
        });
        const service = google.drive({version: 'v3', auth});
        const fileMetadata = {
          name: 'photo.jpg',
        };
        const media = {
          mimeType: 'image/jpeg',
          body: fs.createReadStream('files/photo.jpg'),
        };
        try {
          const file = await service.files.create({
            resource: fileMetadata,
            media: media,
            fields: 'id',
          });
          console.log('File Id:', file.data.id);
          return file.data.id;
        } catch (err) {
          // TODO(developer) - Handle error
          throw err;
        }
      }
      9. Required unless you use chunked transfer encoding. Set to the number of bytes in the body of this initial request.
  4. Send the request. If the session initiation request succeeds, the response includes a

    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_with_conversion():
        """Upload file with conversion
        Returns: ID of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {
                'name': 'My Report',
                'mimeType': 'application/vnd.google-apps.spreadsheet'
            }
            media = MediaFileUpload('report.csv', mimetype='text/csv',
                                    resumable=True)
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File with ID: "{file.get("id")}" has been uploaded.')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_with_conversion()
    0 status code. In addition, the response includes a
    import com.google.api.client.googleapis.json.GoogleJsonResponseException;
    import com.google.api.client.http.FileContent;
    import com.google.api.client.http.HttpRequestInitializer;
    import com.google.api.client.http.javanet.NetHttpTransport;
    import com.google.api.client.json.gson.GsonFactory;
    import com.google.api.services.drive.Drive;
    import com.google.api.services.drive.DriveScopes;
    import com.google.api.services.drive.model.File;
    import com.google.auth.http.HttpCredentialsAdapter;
    import com.google.auth.oauth2.GoogleCredentials;
    import java.io.IOException;
    import java.util.Arrays;
    
    /* Class to demonstrate Drive's upload with conversion use-case. */
    public class UploadWithConversion {
    
      /**
       * Upload file with conversion.
       *
       * @return Inserted file id if successful, {@code null} otherwise.
       * @throws IOException if service account credentials file not found.
       */
      public static String uploadWithConversion() throws IOException {
        // Load pre-authorized user credentials from the environment.
        // TODO(developer) - See https://developers.google.com/identity for
        // guides on implementing OAuth2 for your application.
        GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
            .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));
        HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
            credentials);
    
        // Build a new authorized API client service.
        Drive service = new Drive.Builder(new NetHttpTransport(),
            GsonFactory.getDefaultInstance(),
            requestInitializer)
            .setApplicationName("Drive samples")
            .build();
    
        // File's metadata.
        File fileMetadata = new File();
        fileMetadata.setName("My Report");
        fileMetadata.setMimeType("application/vnd.google-apps.spreadsheet");
    
        java.io.File filePath = new java.io.File("files/report.csv");
        FileContent mediaContent = new FileContent("text/csv", filePath);
        try {
          File file = service.files().create(fileMetadata, mediaContent)
              .setFields("id")
              .execute();
          System.out.println("File ID: " + file.getId());
          return file.getId();
        } catch (GoogleJsonResponseException e) {
          // TODO(developer) - handle error appropriately
          System.err.println("Unable to move file: " + e.getDetails());
          throw e;
        }
      }
    }
    1 header that specifies the resumable session URI. Use the resumable session URI to upload the file data and query the upload status. A resumable session URI expires after one week.

  5. Copy and save the resumable session URL.

  6. Continue to Upload the content.

Upload the content

There are 2 ways to upload a file with a resumable session:

  • Upload content in a single request—Use this approach when the file can be uploaded in one request, if there's no fixed time limit for any single request, or you don't need to display an upload progress indicator. This approach is best because it requires fewer requests and results in better performance.
  • Upload the content in multiple chunks—Use this approach if you must reduce the amount of data transferred in any single request. You might need to reduce data transferred when there's a fixed time limit for individual requests, as can be the case for certain classes of App Engine requests. This approach is also useful if you must provide a customized indicator to show the upload progress.

HTTP - single request

  1. Create a
    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_basic():
        """Insert new file.
        Returns : Id's of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {'name': 'download.jpeg'}
            media = MediaFileUpload('download.jpeg',
                                    mimetype='image/jpeg')
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File ID: {file.get("id")}')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_basic()
    8 request to the resumable session URI.
  2. Add the file's data to the request body.
  3. Add a Content-Length HTTP header, set to the number of bytes in the file.
  4. Send the request. If the upload request is interrupted, or if you receive a
    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_with_conversion():
        """Upload file with conversion
        Returns: ID of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {
                'name': 'My Report',
                'mimeType': 'application/vnd.google-apps.spreadsheet'
            }
            media = MediaFileUpload('report.csv', mimetype='text/csv',
                                    resumable=True)
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File with ID: "{file.get("id")}" has been uploaded.')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_with_conversion()
    3 response, follow the procedure in Resume an interrupted upload.

HTTP - multiple requests

  1. Create a

    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_basic():
        """Insert new file.
        Returns : Id's of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {'name': 'download.jpeg'}
            media = MediaFileUpload('download.jpeg',
                                    mimetype='image/jpeg')
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File ID: {file.get("id")}')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_basic()
    8 request to the resumable session URI.

  2. Add the chunk's data to the request body. Create chunks in multiples of 256 KB (256 x 1024 bytes) in size, except for the final chunk that completes the upload. Keep the chunk size as large as possible so that the upload is efficient.

  3. Add these HTTP headers:

    • /**
       * Insert new file.
       * @return{obj} file Id
       * */
      async function uploadBasic() {
        const fs = require('fs');
        const {GoogleAuth} = require('google-auth-library');
        const {google} = require('googleapis');
      
        // Get credentials and build service
        // TODO (developer) - Use appropriate auth mechanism for your app
        const auth = new GoogleAuth({
          scopes: 'https://www.googleapis.com/auth/drive',
        });
        const service = google.drive({version: 'v3', auth});
        const fileMetadata = {
          name: 'photo.jpg',
        };
        const media = {
          mimeType: 'image/jpeg',
          body: fs.createReadStream('files/photo.jpg'),
        };
        try {
          const file = await service.files.create({
            resource: fileMetadata,
            media: media,
            fields: 'id',
          });
          console.log('File Id:', file.data.id);
          return file.data.id;
        } catch (err) {
          // TODO(developer) - Handle error
          throw err;
        }
      }
      9. Set to the number of bytes in the current chunk.
    • from __future__ import print_function
      
      import google.auth
      from googleapiclient.discovery import build
      from googleapiclient.errors import HttpError
      from googleapiclient.http import MediaFileUpload
      
      
      def upload_with_conversion():
          """Upload file with conversion
          Returns: ID of the file uploaded
      
          Load pre-authorized user credentials from the environment.
          TODO(developer) - See https://developers.google.com/identity
          for guides on implementing OAuth2 for the application.
          """
          creds, _ = google.auth.default()
      
          try:
              # create drive api client
              service = build('drive', 'v3', credentials=creds)
      
              file_metadata = {
                  'name': 'My Report',
                  'mimeType': 'application/vnd.google-apps.spreadsheet'
              }
              media = MediaFileUpload('report.csv', mimetype='text/csv',
                                      resumable=True)
              # pylint: disable=maybe-no-member
              file = service.files().create(body=file_metadata, media_body=media,
                                            fields='id').execute()
              print(F'File with ID: "{file.get("id")}" has been uploaded.')
      
          except HttpError as error:
              print(F'An error occurred: {error}')
              file = None
      
          return file.get('id')
      
      
      if __name__ == '__main__':
          upload_with_conversion()
      6. Set to show which bytes in the file you upload. For example,
      from __future__ import print_function
      
      import google.auth
      from googleapiclient.discovery import build
      from googleapiclient.errors import HttpError
      from googleapiclient.http import MediaFileUpload
      
      
      def upload_with_conversion():
          """Upload file with conversion
          Returns: ID of the file uploaded
      
          Load pre-authorized user credentials from the environment.
          TODO(developer) - See https://developers.google.com/identity
          for guides on implementing OAuth2 for the application.
          """
          creds, _ = google.auth.default()
      
          try:
              # create drive api client
              service = build('drive', 'v3', credentials=creds)
      
              file_metadata = {
                  'name': 'My Report',
                  'mimeType': 'application/vnd.google-apps.spreadsheet'
              }
              media = MediaFileUpload('report.csv', mimetype='text/csv',
                                      resumable=True)
              # pylint: disable=maybe-no-member
              file = service.files().create(body=file_metadata, media_body=media,
                                            fields='id').execute()
              print(F'File with ID: "{file.get("id")}" has been uploaded.')
      
          except HttpError as error:
              print(F'An error occurred: {error}')
              file = None
      
          return file.get('id')
      
      
      if __name__ == '__main__':
          upload_with_conversion()
      7 shows that you upload the first 524,288 bytes (256 x 1024 x 2) in a 2,000,000 byte file.
  4. Send the request, and process the response. If the upload request is interrupted, or if you receive a

    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_with_conversion():
        """Upload file with conversion
        Returns: ID of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {
                'name': 'My Report',
                'mimeType': 'application/vnd.google-apps.spreadsheet'
            }
            media = MediaFileUpload('report.csv', mimetype='text/csv',
                                    resumable=True)
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File with ID: "{file.get("id")}" has been uploaded.')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_with_conversion()
    3 response, follow the procedure in Resume an interrupted upload.

  5. Repeat steps 1 through 4 for each chunk that remains in the file. Use the

    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_with_conversion():
        """Upload file with conversion
        Returns: ID of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {
                'name': 'My Report',
                'mimeType': 'application/vnd.google-apps.spreadsheet'
            }
            media = MediaFileUpload('report.csv', mimetype='text/csv',
                                    resumable=True)
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File with ID: "{file.get("id")}" has been uploaded.')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_with_conversion()
    9 header in the response to determine where to start the next chunk. Don't assume that the server received all bytes sent in the previous request.

When the entire file upload is complete, you receive a

import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Arrays;

/* Class to demonstrate Drive's upload with conversion use-case. */
public class UploadWithConversion {

  /**
   * Upload file with conversion.
   *
   * @return Inserted file id if successful, {@code null} otherwise.
   * @throws IOException if service account credentials file not found.
   */
  public static String uploadWithConversion() throws IOException {
    // Load pre-authorized user credentials from the environment.
    // TODO(developer) - See https://developers.google.com/identity for
    // guides on implementing OAuth2 for your application.
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
        .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
        credentials);

    // Build a new authorized API client service.
    Drive service = new Drive.Builder(new NetHttpTransport(),
        GsonFactory.getDefaultInstance(),
        requestInitializer)
        .setApplicationName("Drive samples")
        .build();

    // File's metadata.
    File fileMetadata = new File();
    fileMetadata.setName("My Report");
    fileMetadata.setMimeType("application/vnd.google-apps.spreadsheet");

    java.io.File filePath = new java.io.File("files/report.csv");
    FileContent mediaContent = new FileContent("text/csv", filePath);
    try {
      File file = service.files().create(fileMetadata, mediaContent)
          .setFields("id")
          .execute();
      System.out.println("File ID: " + file.getId());
      return file.getId();
    } catch (GoogleJsonResponseException e) {
      // TODO(developer) - handle error appropriately
      System.err.println("Unable to move file: " + e.getDetails());
      throw e;
    }
  }
}
0 or
/**
 * Upload file with conversion
 * @return{obj} file Id
 * */
async function uploadWithConversion() {
  const fs = require('fs');
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');
  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});
  const fileMetadata = {
    name: 'My Report',
    mimeType: 'application/vnd.google-apps.spreadsheet',
  };
  const media = {
    mimeType: 'text/csv',
    body: fs.createReadStream('files/report.csv'),
  };

  try {
    const file = await service.files.create({
      resource: fileMetadata,
      media: media,
      fields: 'id',
    });
    console.log('File Id:', file.data.id);
    return file.data.id;
  } catch (err) {
    // TODO(developer) - Handle error
    throw err;
  }
}
1 response, along with any metadata associated with the resource.

Resume an interrupted upload

If an upload request is terminated before a response, or if you receive a

/**
 * Upload file with conversion
 * @return{obj} file Id
 * */
async function uploadWithConversion() {
  const fs = require('fs');
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');
  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});
  const fileMetadata = {
    name: 'My Report',
    mimeType: 'application/vnd.google-apps.spreadsheet',
  };
  const media = {
    mimeType: 'text/csv',
    body: fs.createReadStream('files/report.csv'),
  };

  try {
    const file = await service.files.create({
      resource: fileMetadata,
      media: media,
      fields: 'id',
    });
    console.log('File Id:', file.data.id);
    return file.data.id;
  } catch (err) {
    // TODO(developer) - Handle error
    throw err;
  }
}
2 response, then you must resume the interrupted upload.

HTTP

  1. To request the upload status, create an empty

    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_basic():
        """Insert new file.
        Returns : Id's of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {'name': 'download.jpeg'}
            media = MediaFileUpload('download.jpeg',
                                    mimetype='image/jpeg')
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File ID: {file.get("id")}')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_basic()
    8 request to the resumable session URI.

  2. Add a

    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_with_conversion():
        """Upload file with conversion
        Returns: ID of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {
                'name': 'My Report',
                'mimeType': 'application/vnd.google-apps.spreadsheet'
            }
            media = MediaFileUpload('report.csv', mimetype='text/csv',
                                    resumable=True)
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File with ID: "{file.get("id")}" has been uploaded.')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_with_conversion()
    6 header to indicate that the current position in the file is unknown. For example, set the
    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_with_conversion():
        """Upload file with conversion
        Returns: ID of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {
                'name': 'My Report',
                'mimeType': 'application/vnd.google-apps.spreadsheet'
            }
            media = MediaFileUpload('report.csv', mimetype='text/csv',
                                    resumable=True)
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File with ID: "{file.get("id")}" has been uploaded.')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_with_conversion()
    6 to
    /**
     * Upload file with conversion
     * @return{obj} file Id
     * */
    async function uploadWithConversion() {
      const fs = require('fs');
      const {GoogleAuth} = require('google-auth-library');
      const {google} = require('googleapis');
      // Get credentials and build service
      // TODO (developer) - Use appropriate auth mechanism for your app
      const auth = new GoogleAuth({
        scopes: 'https://www.googleapis.com/auth/drive',
      });
      const service = google.drive({version: 'v3', auth});
      const fileMetadata = {
        name: 'My Report',
        mimeType: 'application/vnd.google-apps.spreadsheet',
      };
      const media = {
        mimeType: 'text/csv',
        body: fs.createReadStream('files/report.csv'),
      };
    
      try {
        const file = await service.files.create({
          resource: fileMetadata,
          media: media,
          fields: 'id',
        });
        console.log('File Id:', file.data.id);
        return file.data.id;
      } catch (err) {
        // TODO(developer) - Handle error
        throw err;
      }
    }
    6 if your total file length is 2,000,000 bytes. If you don't know the full size of the file, set the
    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_with_conversion():
        """Upload file with conversion
        Returns: ID of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {
                'name': 'My Report',
                'mimeType': 'application/vnd.google-apps.spreadsheet'
            }
            media = MediaFileUpload('report.csv', mimetype='text/csv',
                                    resumable=True)
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File with ID: "{file.get("id")}" has been uploaded.')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_with_conversion()
    6 to
    /**
     * Upload file with conversion
     * @return{obj} file Id
     * */
    async function uploadWithConversion() {
      const fs = require('fs');
      const {GoogleAuth} = require('google-auth-library');
      const {google} = require('googleapis');
      // Get credentials and build service
      // TODO (developer) - Use appropriate auth mechanism for your app
      const auth = new GoogleAuth({
        scopes: 'https://www.googleapis.com/auth/drive',
      });
      const service = google.drive({version: 'v3', auth});
      const fileMetadata = {
        name: 'My Report',
        mimeType: 'application/vnd.google-apps.spreadsheet',
      };
      const media = {
        mimeType: 'text/csv',
        body: fs.createReadStream('files/report.csv'),
      };
    
      try {
        const file = await service.files.create({
          resource: fileMetadata,
          media: media,
          fields: 'id',
        });
        console.log('File Id:', file.data.id);
        return file.data.id;
      } catch (err) {
        // TODO(developer) - Handle error
        throw err;
      }
    }
    8.

  3. Send the request.

  4. Process the response:

    • A
      import com.google.api.client.googleapis.json.GoogleJsonResponseException;
      import com.google.api.client.http.FileContent;
      import com.google.api.client.http.HttpRequestInitializer;
      import com.google.api.client.http.javanet.NetHttpTransport;
      import com.google.api.client.json.gson.GsonFactory;
      import com.google.api.services.drive.Drive;
      import com.google.api.services.drive.DriveScopes;
      import com.google.api.services.drive.model.File;
      import com.google.auth.http.HttpCredentialsAdapter;
      import com.google.auth.oauth2.GoogleCredentials;
      import java.io.IOException;
      import java.util.Arrays;
      
      /* Class to demonstrate Drive's upload with conversion use-case. */
      public class UploadWithConversion {
      
        /**
         * Upload file with conversion.
         *
         * @return Inserted file id if successful, {@code null} otherwise.
         * @throws IOException if service account credentials file not found.
         */
        public static String uploadWithConversion() throws IOException {
          // Load pre-authorized user credentials from the environment.
          // TODO(developer) - See https://developers.google.com/identity for
          // guides on implementing OAuth2 for your application.
          GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
              .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));
          HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
              credentials);
      
          // Build a new authorized API client service.
          Drive service = new Drive.Builder(new NetHttpTransport(),
              GsonFactory.getDefaultInstance(),
              requestInitializer)
              .setApplicationName("Drive samples")
              .build();
      
          // File's metadata.
          File fileMetadata = new File();
          fileMetadata.setName("My Report");
          fileMetadata.setMimeType("application/vnd.google-apps.spreadsheet");
      
          java.io.File filePath = new java.io.File("files/report.csv");
          FileContent mediaContent = new FileContent("text/csv", filePath);
          try {
            File file = service.files().create(fileMetadata, mediaContent)
                .setFields("id")
                .execute();
            System.out.println("File ID: " + file.getId());
            return file.getId();
          } catch (GoogleJsonResponseException e) {
            // TODO(developer) - handle error appropriately
            System.err.println("Unable to move file: " + e.getDetails());
            throw e;
          }
        }
      }
      0 or
      /**
       * Upload file with conversion
       * @return{obj} file Id
       * */
      async function uploadWithConversion() {
        const fs = require('fs');
        const {GoogleAuth} = require('google-auth-library');
        const {google} = require('googleapis');
        // Get credentials and build service
        // TODO (developer) - Use appropriate auth mechanism for your app
        const auth = new GoogleAuth({
          scopes: 'https://www.googleapis.com/auth/drive',
        });
        const service = google.drive({version: 'v3', auth});
        const fileMetadata = {
          name: 'My Report',
          mimeType: 'application/vnd.google-apps.spreadsheet',
        };
        const media = {
          mimeType: 'text/csv',
          body: fs.createReadStream('files/report.csv'),
        };
      
        try {
          const file = await service.files.create({
            resource: fileMetadata,
            media: media,
            fields: 'id',
          });
          console.log('File Id:', file.data.id);
          return file.data.id;
        } catch (err) {
          // TODO(developer) - Handle error
          throw err;
        }
      }
      1 response indicates that the upload was completed, and no further action is necessary.
    • A
      use Google\Client;
      use Google\Service\Drive;
      function uploadWithConversion()
      {
          try {
              $client = new Client();
              $client->useApplicationDefaultCredentials();
              $client->addScope(Drive::DRIVE);
              $driveService = new Drive($client);
              $fileMetadata = new Drive\DriveFile(array(
                  'name' => 'My Report',
                  'mimeType' => 'application/vnd.google-apps.spreadsheet'));
              $content = file_get_contents('../files/report.csv');
              $file = $driveService->files->create($fileMetadata, array(
                  'data' => $content,
                  'mimeType' => 'text/csv',
                  'uploadType' => 'multipart',
                  'fields' => 'id'));
              printf("File ID: %s\n", $file->id);
              return $file->id;
          } catch(Exception $e) {
              echo "Error Message: ".$e;
          }
      
      }
      1 response indicates that you need to continue to upload the file.
    • A
      use Google\Client;
      use Google\Service\Drive;
      function uploadWithConversion()
      {
          try {
              $client = new Client();
              $client->useApplicationDefaultCredentials();
              $client->addScope(Drive::DRIVE);
              $driveService = new Drive($client);
              $fileMetadata = new Drive\DriveFile(array(
                  'name' => 'My Report',
                  'mimeType' => 'application/vnd.google-apps.spreadsheet'));
              $content = file_get_contents('../files/report.csv');
              $file = $driveService->files->create($fileMetadata, array(
                  'data' => $content,
                  'mimeType' => 'text/csv',
                  'uploadType' => 'multipart',
                  'fields' => 'id'));
              printf("File ID: %s\n", $file->id);
              return $file->id;
          } catch(Exception $e) {
              echo "Error Message: ".$e;
          }
      
      }
      2 response indicates the upload session has expired and the upload must be restarted from the beginning.
  5. If you received a

    use Google\Client;
    use Google\Service\Drive;
    function uploadWithConversion()
    {
        try {
            $client = new Client();
            $client->useApplicationDefaultCredentials();
            $client->addScope(Drive::DRIVE);
            $driveService = new Drive($client);
            $fileMetadata = new Drive\DriveFile(array(
                'name' => 'My Report',
                'mimeType' => 'application/vnd.google-apps.spreadsheet'));
            $content = file_get_contents('../files/report.csv');
            $file = $driveService->files->create($fileMetadata, array(
                'data' => $content,
                'mimeType' => 'text/csv',
                'uploadType' => 'multipart',
                'fields' => 'id'));
            printf("File ID: %s\n", $file->id);
            return $file->id;
        } catch(Exception $e) {
            echo "Error Message: ".$e;
        }
    
    }
    1 response, process the
    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_with_conversion():
        """Upload file with conversion
        Returns: ID of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {
                'name': 'My Report',
                'mimeType': 'application/vnd.google-apps.spreadsheet'
            }
            media = MediaFileUpload('report.csv', mimetype='text/csv',
                                    resumable=True)
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File with ID: "{file.get("id")}" has been uploaded.')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_with_conversion()
    9 header of the response to determine which bytes the server has received. If the response doesn't have a
    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_with_conversion():
        """Upload file with conversion
        Returns: ID of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {
                'name': 'My Report',
                'mimeType': 'application/vnd.google-apps.spreadsheet'
            }
            media = MediaFileUpload('report.csv', mimetype='text/csv',
                                    resumable=True)
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File with ID: "{file.get("id")}" has been uploaded.')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_with_conversion()
    9 header, no bytes have been received. For example, a
    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_with_conversion():
        """Upload file with conversion
        Returns: ID of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {
                'name': 'My Report',
                'mimeType': 'application/vnd.google-apps.spreadsheet'
            }
            media = MediaFileUpload('report.csv', mimetype='text/csv',
                                    resumable=True)
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File with ID: "{file.get("id")}" has been uploaded.')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_with_conversion()
    9 header of
    use Google\Client;
    use Google\Service\Drive;
    function uploadWithConversion()
    {
        try {
            $client = new Client();
            $client->useApplicationDefaultCredentials();
            $client->addScope(Drive::DRIVE);
            $driveService = new Drive($client);
            $fileMetadata = new Drive\DriveFile(array(
                'name' => 'My Report',
                'mimeType' => 'application/vnd.google-apps.spreadsheet'));
            $content = file_get_contents('../files/report.csv');
            $file = $driveService->files->create($fileMetadata, array(
                'data' => $content,
                'mimeType' => 'text/csv',
                'uploadType' => 'multipart',
                'fields' => 'id'));
            printf("File ID: %s\n", $file->id);
            return $file->id;
        } catch(Exception $e) {
            echo "Error Message: ".$e;
        }
    
    }
    7 indicates that the first 43 bytes of the file were received and that the next chunk to upload would start with byte 44.

  6. Now that you know where to resume the upload, continue to upload the file beginning with the next byte. Include a

    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_with_conversion():
        """Upload file with conversion
        Returns: ID of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {
                'name': 'My Report',
                'mimeType': 'application/vnd.google-apps.spreadsheet'
            }
            media = MediaFileUpload('report.csv', mimetype='text/csv',
                                    resumable=True)
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File with ID: "{file.get("id")}" has been uploaded.')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_with_conversion()
    6 header to indicate which portion of the file you send. For example,
    use Google\Client;
    use Google\Service\Drive;
    function uploadWithConversion()
    {
        try {
            $client = new Client();
            $client->useApplicationDefaultCredentials();
            $client->addScope(Drive::DRIVE);
            $driveService = new Drive($client);
            $fileMetadata = new Drive\DriveFile(array(
                'name' => 'My Report',
                'mimeType' => 'application/vnd.google-apps.spreadsheet'));
            $content = file_get_contents('../files/report.csv');
            $file = $driveService->files->create($fileMetadata, array(
                'data' => $content,
                'mimeType' => 'text/csv',
                'uploadType' => 'multipart',
                'fields' => 'id'));
            printf("File ID: %s\n", $file->id);
            return $file->id;
        } catch(Exception $e) {
            echo "Error Message: ".$e;
        }
    
    }
    9 indicates that you send bytes 44 through 2,000,000.

Handle media upload errors

When you upload media, follow these best practices to handle errors:

  • For
    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_with_conversion():
        """Upload file with conversion
        Returns: ID of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {
                'name': 'My Report',
                'mimeType': 'application/vnd.google-apps.spreadsheet'
            }
            media = MediaFileUpload('report.csv', mimetype='text/csv',
                                    resumable=True)
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File with ID: "{file.get("id")}" has been uploaded.')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_with_conversion()
    3 errors, resume or retry uploads that fail due to connection interruptions. For further information on handling
    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_with_conversion():
        """Upload file with conversion
        Returns: ID of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {
                'name': 'My Report',
                'mimeType': 'application/vnd.google-apps.spreadsheet'
            }
            media = MediaFileUpload('report.csv', mimetype='text/csv',
                                    resumable=True)
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File with ID: "{file.get("id")}" has been uploaded.')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_with_conversion()
    3 errors, refer to Resolve a
    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_with_conversion():
        """Upload file with conversion
        Returns: ID of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {
                'name': 'My Report',
                'mimeType': 'application/vnd.google-apps.spreadsheet'
            }
            media = MediaFileUpload('report.csv', mimetype='text/csv',
                                    resumable=True)
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File with ID: "{file.get("id")}" has been uploaded.')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_with_conversion()
    3 error.
  • For
    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_basic():
        """Insert new file.
        Returns : Id's of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {'name': 'download.jpeg'}
            media = MediaFileUpload('download.jpeg',
                                    mimetype='image/jpeg')
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File ID: {file.get("id")}')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_basic()
    03 errors, retry the upload. For further information about handling
    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_basic():
        """Insert new file.
        Returns : Id's of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {'name': 'download.jpeg'}
            media = MediaFileUpload('download.jpeg',
                                    mimetype='image/jpeg')
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File ID: {file.get("id")}')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_basic()
    03 errors, refer to Resolve a
    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_basic():
        """Insert new file.
        Returns : Id's of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {'name': 'download.jpeg'}
            media = MediaFileUpload('download.jpeg',
                                    mimetype='image/jpeg')
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File ID: {file.get("id")}')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_basic()
    05.
  • For any
    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_basic():
        """Insert new file.
        Returns : Id's of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {'name': 'download.jpeg'}
            media = MediaFileUpload('download.jpeg',
                                    mimetype='image/jpeg')
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File ID: {file.get("id")}')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_basic()
    06 errors (including
    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from googleapiclient.http import MediaFileUpload
    
    
    def upload_basic():
        """Insert new file.
        Returns : Id's of the file uploaded
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
    
            file_metadata = {'name': 'download.jpeg'}
            media = MediaFileUpload('download.jpeg',
                                    mimetype='image/jpeg')
            # pylint: disable=maybe-no-member
            file = service.files().create(body=file_metadata, media_body=media,
                                          fields='id').execute()
            print(F'File ID: {file.get("id")}')
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            file = None
    
        return file.get('id')
    
    
    if __name__ == '__main__':
        upload_basic()
    07) during a resumable upload, restart the upload. These errors indicate the upload session has expired and must be restarted by requesting a new session URI. Upload sessions also expire after one week of inactivity.

Import to Google Docs types

When you create a file in Drive, you might want to convert the file into a Google Workspace file type, such as a Google Doc or Google Sheet. For example, maybe you want to convert a document from your favorite word processor into a Google Doc to take advantage of its features.

To convert a file to a specific Google Workspace file type, specify the Google Workspace

from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_basic():
    """Insert new file.
    Returns : Id's of the file uploaded

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_metadata = {'name': 'download.jpeg'}
        media = MediaFileUpload('download.jpeg',
                                mimetype='image/jpeg')
        # pylint: disable=maybe-no-member
        file = service.files().create(body=file_metadata, media_body=media,
                                      fields='id').execute()
        print(F'File ID: {file.get("id")}')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.get('id')


if __name__ == '__main__':
    upload_basic()
08 when creating the file.

Note: If you're using the older Drive API v2, include the
/**
 * Insert new file.
 * @return{obj} file Id
 * */
async function uploadBasic() {
  const fs = require('fs');
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});
  const fileMetadata = {
    name: 'photo.jpg',
  };
  const media = {
    mimeType: 'image/jpeg',
    body: fs.createReadStream('files/photo.jpg'),
  };
  try {
    const file = await service.files.create({
      resource: fileMetadata,
      media: media,
      fields: 'id',
    });
    console.log('File Id:', file.data.id);
    return file.data.id;
  } catch (err) {
    // TODO(developer) - Handle error
    throw err;
  }
}
4
from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_basic():
    """Insert new file.
    Returns : Id's of the file uploaded

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_metadata = {'name': 'download.jpeg'}
        media = MediaFileUpload('download.jpeg',
                                mimetype='image/jpeg')
        # pylint: disable=maybe-no-member
        file = service.files().create(body=file_metadata, media_body=media,
                                      fields='id').execute()
        print(F'File ID: {file.get("id")}')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.get('id')


if __name__ == '__main__':
    upload_basic()
10 query parameter and specify the Google Workspace
from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_basic():
    """Insert new file.
    Returns : Id's of the file uploaded

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_metadata = {'name': 'download.jpeg'}
        media = MediaFileUpload('download.jpeg',
                                mimetype='image/jpeg')
        # pylint: disable=maybe-no-member
        file = service.files().create(body=file_metadata, media_body=media,
                                      fields='id').execute()
        print(F'File ID: {file.get("id")}')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.get('id')


if __name__ == '__main__':
    upload_basic()
08 when creating the file.

The following shows how to convert a CSV file to a Google Workspace sheet:

Note: If you're using the older Drive API v2, you can find code samples in GitHub. Learn how to migrate to Drive API v3.

Java

drive/snippets/drive_v3/src/main/java/UploadWithConversion.java

View on GitHub

import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Arrays;

/* Class to demonstrate Drive's upload with conversion use-case. */
public class UploadWithConversion {

  /**
   * Upload file with conversion.
   *
   * @return Inserted file id if successful, {@code null} otherwise.
   * @throws IOException if service account credentials file not found.
   */
  public static String uploadWithConversion() throws IOException {
    // Load pre-authorized user credentials from the environment.
    // TODO(developer) - See https://developers.google.com/identity for
    // guides on implementing OAuth2 for your application.
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
        .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
        credentials);

    // Build a new authorized API client service.
    Drive service = new Drive.Builder(new NetHttpTransport(),
        GsonFactory.getDefaultInstance(),
        requestInitializer)
        .setApplicationName("Drive samples")
        .build();

    // File's metadata.
    File fileMetadata = new File();
    fileMetadata.setName("My Report");
    fileMetadata.setMimeType("application/vnd.google-apps.spreadsheet");

    java.io.File filePath = new java.io.File("files/report.csv");
    FileContent mediaContent = new FileContent("text/csv", filePath);
    try {
      File file = service.files().create(fileMetadata, mediaContent)
          .setFields("id")
          .execute();
      System.out.println("File ID: " + file.getId());
      return file.getId();
    } catch (GoogleJsonResponseException e) {
      // TODO(developer) - handle error appropriately
      System.err.println("Unable to move file: " + e.getDetails());
      throw e;
    }
  }
}

Python

drive/snippets/drive-v3/file_snippet/upload_with_conversion.py

View on GitHub

from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_with_conversion():
    """Upload file with conversion
    Returns: ID of the file uploaded

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_metadata = {
            'name': 'My Report',
            'mimeType': 'application/vnd.google-apps.spreadsheet'
        }
        media = MediaFileUpload('report.csv', mimetype='text/csv',
                                resumable=True)
        # pylint: disable=maybe-no-member
        file = service.files().create(body=file_metadata, media_body=media,
                                      fields='id').execute()
        print(F'File with ID: "{file.get("id")}" has been uploaded.')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.get('id')


if __name__ == '__main__':
    upload_with_conversion()

Node.js

drive/snippets/drive_v3/file_snippets/upload_with_conversion.js

View on GitHub

/**
 * Upload file with conversion
 * @return{obj} file Id
 * */
async function uploadWithConversion() {
  const fs = require('fs');
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');
  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});
  const fileMetadata = {
    name: 'My Report',
    mimeType: 'application/vnd.google-apps.spreadsheet',
  };
  const media = {
    mimeType: 'text/csv',
    body: fs.createReadStream('files/report.csv'),
  };

  try {
    const file = await service.files.create({
      resource: fileMetadata,
      media: media,
      fields: 'id',
    });
    console.log('File Id:', file.data.id);
    return file.data.id;
  } catch (err) {
    // TODO(developer) - Handle error
    throw err;
  }
}

PHP

drive/snippets/drive_v3/src/DriveUploadWithConversion.php

View on GitHub

use Google\Client;
use Google\Service\Drive;
function uploadWithConversion()
{
    try {
        $client = new Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope(Drive::DRIVE);
        $driveService = new Drive($client);
        $fileMetadata = new Drive\DriveFile(array(
            'name' => 'My Report',
            'mimeType' => 'application/vnd.google-apps.spreadsheet'));
        $content = file_get_contents('../files/report.csv');
        $file = $driveService->files->create($fileMetadata, array(
            'data' => $content,
            'mimeType' => 'text/csv',
            'uploadType' => 'multipart',
            'fields' => 'id'));
        printf("File ID: %s\n", $file->id);
        return $file->id;
    } catch(Exception $e) {
        echo "Error Message: ".$e;
    }

}

.NET

drive/snippets/drive_v3/DriveV3Snippets/UploadWithConversion.cs

View on GitHub

from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_basic():
    """Insert new file.
    Returns : Id's of the file uploaded

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_metadata = {'name': 'download.jpeg'}
        media = MediaFileUpload('download.jpeg',
                                mimetype='image/jpeg')
        # pylint: disable=maybe-no-member
        file = service.files().create(body=file_metadata, media_body=media,
                                      fields='id').execute()
        print(F'File ID: {file.get("id")}')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.get('id')


if __name__ == '__main__':
    upload_basic()
0

To see if a conversion is available, check the About resource's

from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_basic():
    """Insert new file.
    Returns : Id's of the file uploaded

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_metadata = {'name': 'download.jpeg'}
        media = MediaFileUpload('download.jpeg',
                                mimetype='image/jpeg')
        # pylint: disable=maybe-no-member
        file = service.files().create(body=file_metadata, media_body=media,
                                      fields='id').execute()
        print(F'File ID: {file.get("id")}')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.get('id')


if __name__ == '__main__':
    upload_basic()
12 array before creating the file. Supported conversions are available dynamically in this array. Some common import formats are:

FromToMicrosoft Word, OpenDocument Text, HTML, RTF, plain textGoogle DocsMicrosoft Excel, OpenDocument Spreadsheet, CSV, TSV, plain textGoogle SheetsMicrosoft PowerPoint, OpenDocument PresentationGoogle SlidesJPEG, PNG, GIF, BMP, PDFGoogle Docs (embeds the image in a Doc)Plain text (special MIME type), JSONGoogle Apps Script

When you upload and convert media during an

from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_basic():
    """Insert new file.
    Returns : Id's of the file uploaded

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_metadata = {'name': 'download.jpeg'}
        media = MediaFileUpload('download.jpeg',
                                mimetype='image/jpeg')
        # pylint: disable=maybe-no-member
        file = service.files().create(body=file_metadata, media_body=media,
                                      fields='id').execute()
        print(F'File ID: {file.get("id")}')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.get('id')


if __name__ == '__main__':
    upload_basic()
13 request to a Doc, Sheet, or Slide, the full contents of the document are replaced.

When you convert an image to a Doc, Drive uses Optical Character Recognition (OCR) to convert the image to text. You can improve the quality of the OCR algorithm by specifying the applicable BCP 47 language code in the

from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_basic():
    """Insert new file.
    Returns : Id's of the file uploaded

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_metadata = {'name': 'download.jpeg'}
        media = MediaFileUpload('download.jpeg',
                                mimetype='image/jpeg')
        # pylint: disable=maybe-no-member
        file = service.files().create(body=file_metadata, media_body=media,
                                      fields='id').execute()
        print(F'File ID: {file.get("id")}')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.get('id')


if __name__ == '__main__':
    upload_basic()
14 parameter. The extracted text appears in the Doc alongside the embedded image.

Use a pre-generated ID to upload files

The Drive API lets you retrieve a list of pre-generated file IDs that are used to upload and create resources. Upload and file creation requests can use these pre-generated IDs. Set the

from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_basic():
    """Insert new file.
    Returns : Id's of the file uploaded

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_metadata = {'name': 'download.jpeg'}
        media = MediaFileUpload('download.jpeg',
                                mimetype='image/jpeg')
        # pylint: disable=maybe-no-member
        file = service.files().create(body=file_metadata, media_body=media,
                                      fields='id').execute()
        print(F'File ID: {file.get("id")}')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.get('id')


if __name__ == '__main__':
    upload_basic()
15 field in the file metadata.

To create pre-generated IDs, call file.generateIds with the number of IDs to create.

You can safely retry uploads with pre-generated IDs if there's an indeterminate server error or timeout. If the file was successfully created, subsequent retries return a

from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_basic():
    """Insert new file.
    Returns : Id's of the file uploaded

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_metadata = {'name': 'download.jpeg'}
        media = MediaFileUpload('download.jpeg',
                                mimetype='image/jpeg')
        # pylint: disable=maybe-no-member
        file = service.files().create(body=file_metadata, media_body=media,
                                      fields='id').execute()
        print(F'File ID: {file.get("id")}')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.get('id')


if __name__ == '__main__':
    upload_basic()
16 error and they don't create duplicate files.

Note: Pre-generated IDs aren't supported for built-in Google Document creation, or uploads where conversion to built-in Google Document format is requested.

Define indexable text for unknown file types

Note: Beginning October 31, 2022, indexable text can be shown in result snippets and will affect search results in more places, including Cloud Search and the search overlay in Drive and Gmail.

Users can use the Drive UI to search for document content. You can also use files.list and the

from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_basic():
    """Insert new file.
    Returns : Id's of the file uploaded

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_metadata = {'name': 'download.jpeg'}
        media = MediaFileUpload('download.jpeg',
                                mimetype='image/jpeg')
        # pylint: disable=maybe-no-member
        file = service.files().create(body=file_metadata, media_body=media,
                                      fields='id').execute()
        print(F'File ID: {file.get("id")}')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.get('id')


if __name__ == '__main__':
    upload_basic()
17 field to search for content from your app. For more information, see Search for files and folders.

Drive automatically indexes documents for search when it recognizes the file type, including text documents, PDFs, images with text, and other common types. If your app saves other types of files (such as drawings, video, and shortcuts), you can improve the discoverability by supplying indexable text in the

from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_basic():
    """Insert new file.
    Returns : Id's of the file uploaded

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_metadata = {'name': 'download.jpeg'}
        media = MediaFileUpload('download.jpeg',
                                mimetype='image/jpeg')
        # pylint: disable=maybe-no-member
        file = service.files().create(body=file_metadata, media_body=media,
                                      fields='id').execute()
        print(F'File ID: {file.get("id")}')

    except HttpError as error:
        print(F'An error occurred: {error}')
        file = None

    return file.get('id')


if __name__ == '__main__':
    upload_basic()
18 field of the file.