Upload file data

The Google Drive API lets you upload file data when you create or update aFile. For information about how to create ametadata-only file, such as a folder, seeCreate metadata-only files.

There are three types of uploads you can perform:

  • Simple upload (uploadType=media): Use this upload type to transfer asmall media file (5 MB or less) without supplying metadata. To perform asimple upload, refer toPerform a simple upload.

  • Multipart upload (uploadType=multipart): "Use this upload type totransfer a small file (5 MB or less) along with metadata that describes thefile, in a single request. To perform a multipart upload, refer toPerforma multipart upload.

  • Resumable upload (uploadType=resumable): Use this upload type forlarge files (greater than 5 MB) and when there's a high chance of networkinterruption, such as when creating a file from a mobile app. Resumableuploads are also a good choice for most applications because they also workfor small files at a minimal cost of one additional HTTP request per upload.To perform a resumable upload, refer toPerform a resumableupload.

The Google API client libraries implement at least one of these types ofuploads. Refer to theclient librarydocumentation for additional details about how touse each of the types.

Note: In the Drive API documentation,media refers to all availablefiles with MIME types supported for upload to Drive. For a listof supported MIME types, refer toGoogle Workspace and Drivesupported MIME types.Note: Users can upload any file type to Drive using theDrive UI and Driveattempts to detect and automatically set the MIME type. If the MIME type can'tbe detected, the MIME type is set toapplication/octet-stream.

UsePATCH vs.PUT

As a refresher, the HTTP verbPATCH supports a partial file resource updatewhereas the HTTP verbPUT supports full resource replacement. Note thatPUTcan 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 ofa resumable upload or for the only request of a simple or multipart upload.
  • UsePUT for all subsequent requests for a resumable upload once therequest has started. These requests are uploading content no matter themethod being called.

Perform a simple upload

To perform a simple upload, use thecreatemethod on thefiles resource withuploadType=media.

Note: If you're using the older Drive API v2, use thefiles.insert method. You can find codesamples inGitHub.Learn how tomigrate to Drive API v3.

The following shows how to perform a simple upload:

HTTP

  1. Create aPOST request to the method's /upload URI with the queryparameter ofuploadType=media:

    POST https://www.googleapis.com/upload/drive/v3/files?uploadType=media

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

  3. Add these HTTP headers:

    • Content-Type. Set to the MIME media type of the object beinguploaded.
    • Content-Length. Set to the number of bytes you upload. If you usechunked transfer encoding, this header is not required.
  4. Send the request. If the request succeeds, the server returns theHTTP200 OK status code along with the file's metadata. {HTTP}

Note: To update an existing file, usePATCH.

When you perform a simple upload, basic metadata is created and some attributesare inferred from the file, such as the MIME type ormodifiedTime. You can usea simple upload in cases where you have small files and file metadata isn'timportant.

Perform a multipart upload

A multipart upload request lets you upload metadata and data in the samerequest. 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 thecreate method on thefiles resource withuploadType=multipart.

Note: If you're using the older Drive API v2, use thefiles.insert method. You can find codesamples inGitHub.Learn how tomigrate to Drive API v3.

The following shows how to perform a multipart upload:

Java

drive/snippets/drive_v3/src/main/java/UploadBasic.java
importcom.google.api.client.googleapis.json.GoogleJsonResponseException;importcom.google.api.client.http.FileContent;importcom.google.api.client.http.HttpRequestInitializer;importcom.google.api.client.http.javanet.NetHttpTransport;importcom.google.api.client.json.gson.GsonFactory;importcom.google.api.services.drive.Drive;importcom.google.api.services.drive.DriveScopes;importcom.google.api.services.drive.model.File;importcom.google.auth.http.HttpCredentialsAdapter;importcom.google.auth.oauth2.GoogleCredentials;importjava.io.IOException;importjava.util.Arrays;/* Class to demonstrate use of Drive insert file API */publicclassUploadBasic{/**   * Upload new file.   *   * @return Inserted file metadata if successful, {@code null} otherwise.   * @throws IOException if service account credentials file not found.   */publicstaticStringuploadBasic()throwsIOException{// Load pre-authorized user credentials from the environment.// TODO(developer) - See https://developers.google.com/identity for// guides on implementing OAuth2 for your application.GoogleCredentialscredentials=GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));HttpRequestInitializerrequestInitializer=newHttpCredentialsAdapter(credentials);// Build a new authorized API client service.Driveservice=newDrive.Builder(newNetHttpTransport(),GsonFactory.getDefaultInstance(),requestInitializer).setApplicationName("Drive samples").build();// Upload file photo.jpg on drive.FilefileMetadata=newFile();fileMetadata.setName("photo.jpg");// File's content.java.io.FilefilePath=newjava.io.File("files/photo.jpg");// Specify media type and file-path for file.FileContentmediaContent=newFileContent("image/jpeg",filePath);try{Filefile=service.files().create(fileMetadata,mediaContent).setFields("id").execute();System.out.println("File ID: "+file.getId());returnfile.getId();}catch(GoogleJsonResponseExceptione){// TODO(developer) - handle error appropriatelySystem.err.println("Unable to upload file: "+e.getDetails());throwe;}}}

Python

drive/snippets/drive-v3/file_snippet/upload_basic.py
importgoogle.authfromgoogleapiclient.discoveryimportbuildfromgoogleapiclient.errorsimportHttpErrorfromgoogleapiclient.httpimportMediaFileUploaddefupload_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 clientservice=build("drive","v3",credentials=creds)file_metadata={"name":"download.jpeg"}media=MediaFileUpload("download.jpeg",mimetype="image/jpeg")# pylint: disable=maybe-no-memberfile=(service.files().create(body=file_metadata,media_body=media,fields="id").execute())print(f'File ID:{file.get("id")}')exceptHttpErroraserror:print(f"An error occurred:{error}")file=Nonereturnfile.get("id")if__name__=="__main__":upload_basic()

Node.js

drive/snippets/drive_v3/file_snippets/upload_basic.js
importfsfrom'node:fs';import{GoogleAuth}from'google-auth-library';import{google}from'googleapis';/** * Uploads a file to Google Drive. * @return {Promise<string|null|undefined>} The ID of the uploaded file. */asyncfunctionuploadBasic(){// Authenticate with Google and get an authorized client.// TODO (developer): Use an appropriate auth mechanism for your app.constauth=newGoogleAuth({scopes:'https://www.googleapis.com/auth/drive',});// Create a new Drive API client (v3).constservice=google.drive({version:'v3',auth});// The request body for the file to be uploaded.constrequestBody={name:'photo.jpg',fields:'id',};// The media content to be uploaded.constmedia={mimeType:'image/jpeg',body:fs.createReadStream('files/photo.jpg'),};// Upload the file.constfile=awaitservice.files.create({requestBody,media,});// Print the ID of the uploaded file.console.log('File Id:',file.data.id);returnfile.data.id;}

PHP

drive/snippets/drive_v3/src/DriveUploadBasic.php
<?phpuse Google\Client;use Google\Service\Drive;# TODO - PHP client currently chokes on fetching start page tokenfunction 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
usingGoogle.Apis.Auth.OAuth2;usingGoogle.Apis.Drive.v3;usingGoogle.Apis.Services;namespaceDriveV3Snippets{// Class to demonstrate use of Drive insert file APIpublicclassUploadBasic{/// <summary>/// Upload new file./// </summary>/// <param name="filePath">Image path to upload.</param>/// <returns>Inserted file metadata if successful, null otherwise.</returns>publicstaticstringDriveUploadBasic(stringfilePath){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. */GoogleCredentialcredential=GoogleCredential.GetApplicationDefault().CreateScoped(DriveService.Scope.Drive);// Create Drive API service.varservice=newDriveService(newBaseClientService.Initializer{HttpClientInitializer=credential,ApplicationName="Drive API Snippets"});// Upload file photo.jpg on drive.varfileMetadata=newGoogle.Apis.Drive.v3.Data.File(){Name="photo.jpg"};FilesResource.CreateMediaUploadrequest;// Create a new file on drive.using(varstream=newFileStream(filePath,FileMode.Open)){// Create a new file, with metadata and stream.request=service.Files.Create(fileMetadata,stream,"image/jpeg");request.Fields="id";request.Upload();}varfile=request.ResponseBody;// Prints the uploaded file id.Console.WriteLine("File ID: "+file.Id);returnfile.Id;}catch(Exceptione){// TODO(developer) - handle error appropriatelyif(eisAggregateException){Console.WriteLine("Credential Not found");}elseif(eisFileNotFoundException){Console.WriteLine("File not found");}else{throw;}}returnnull;}}}

HTTP

  1. Create aPOST request to the method's /upload URI with the queryparameter ofuploadType=multipart:

    POST https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart

  2. Create the body of the request. Format the body according to themultipart/related content typeRFC 2387,which contains two parts:

    • Metadata. The metadata must come first and must have aContent-Typeheader set toapplication/json;charset=UTF-8. Add the file's metadatain JSON format.
    • Media. The media must come second and must have aContent-Type headerof any MIME type. Add the file's data to the media part.

    Identify each part with a boundary string, preceded by two hyphens. Inaddition, add two hyphens after the final boundary string.

  3. Add these top-level HTTP headers:

    • Content-Type. Set tomultipart/related and include the boundarystring you're using to identify the different parts of the request. Forexample:Content-Type: multipart/related; boundary=foo_bar_baz
    • Content-Length. 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 aPOST orPATCH request to the standard resource endpoint:https://www.googleapis.com/drive/v3/files If the request succeeds,the server returns theHTTP 200 OK status code along with the file'smetadata.

Note: To update an existing file, usePATCH.

When creating files, they should specify a file extension in the file'snamefield. For example, when creating a photo JPEG file, you might specify somethinglike"name": "photo.jpg" in the metadata. Subsequent calls to theget method return the read-onlyfileExtensionproperty containing the extension originally specified in thename field.

Perform a resumable upload

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

Resumable uploads are useful when your file sizes might vary greatly or whenthere's a fixed time limit for requests (such as mobile OS background tasks andcertain App Engine requests). You might also use resumable uploads forsituations 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 thecreate method on thefiles resource withuploadType=resumable.

Note: If you're using the older Drive API v2, use thefiles.insert method. You can find codesamples inGitHub.Learn how tomigrate to Drive API v3.

HTTP

  1. Create aPOST request to the method's /upload URI with the queryparameter ofuploadType=resumable:

    POSThttps://www.googleapis.com/upload/drive/v3/files?uploadType=resumable

    If the initiation request succeeds, the response includes a200 OKHTTP status code. In addition, it includes aLocation header thatspecifies the resumable session URI:

    HTTP/1.1 200 OKLocation: https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&upload_id=xa298sd_sdlkj2Content-Length: 0

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

    Note: To update an existing file, usePATCH.
  2. If you have metadata for the file, add the metadata to the request bodyin JSON format. Otherwise, leave the request body empty.

  3. Add these HTTP headers:

  4. Send the request. If the session initiation request succeeds, theresponse includes a200 OK HTTP status code. In addition, the responseincludes aLocation header that specifies the resumable session URI.Use the resumable session URI to upload the file data and query theupload status. A resumable session URI expires after one week.

  5. Copy and save the resumable session URL.

  6. Continue toUpload the content.

Upload the content

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

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

HTTP - single request

  1. Create aPUT 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 a5xx response, follow the procedure inResume an interrupted upload.

HTTP - multiple requests

  1. Create aPUT request to the resumable session URI.

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

  3. Add these HTTP headers:

    • Content-Length. Set to the number of bytes in the current chunk.
    • Content-Range. Set to show which bytes in the file you upload. Forexample,Content-Range: bytes 0-524287/2000000 shows that you upload thefirst 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 isinterrupted, or if you receive a5xx response, follow the procedure inResume an interrupted upload.

  5. Repeat steps 1 through 4 for each chunk that remains in the file. Use theRange 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 a200 OK or201 Created 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 a503Service Unavailable response, then you must resume the interrupted upload.

HTTP

  1. To request the upload status, create an emptyPUT request to theresumable session URI.

  2. Add aContent-Range header to indicate that the current position in thefile is unknown. For example, set theContent-Range to*/2000000 if yourtotal file length is 2,000,000 bytes. If you don't know the full size of thefile, set theContent-Range to*/*.

  3. Send the request.

  4. Process the response:

    • A200 OK or201 Created response indicates that the upload wascompleted, and no further action is necessary.
    • A308 Resume Incomplete response indicates that you must continueto upload the file.
    • A404 Not Found response indicates the upload session has expired andthe upload must be restarted from the beginning.
  5. If you received a308 Resume Incomplete response, process theRange header of the response to determine which bytes the server has received. If theresponse doesn't have aRange header, no bytes have been received.For example, aRange header ofbytes=0-42 indicates that the first43 bytes of the file were received and that the next chunk to uploadwould start with byte 44.

  6. Now that you know where to resume the upload, continue to upload the filebeginning with the next byte. Include aContent-Range header to indicate which portion of the file you send. Forexample,Content-Range: bytes 43-1999999 indicates that yousend bytes 44 through 2,000,000.

Handle media upload errors

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

  • For5xx errors, resume or retry uploads that fail due to connectioninterruptions. For further information on handling5xx errors, refer to500, 502, 503, 504 errors.
  • For403 rate limit errors, retry the upload. For further information abouthandling403 rate limit errors, refer to403 error:rateLimitExceeded.
  • For any4xx errors (including403) during a resumable upload, restartthe upload. These errors indicate the upload session has expired and must berestarted byrequesting a new session URI. Upload sessionsalso expire after one week of inactivity.

Import to Google Docs types

When you create a file in Drive, you might want to convert thefile into a Google Workspace file type, such as Google Docs orSheets. For example, maybe you want to transform a document fromyour favorite word processor into a Docs to take advantage of itsfeatures.

To convert a file to a specific Google Workspace file type, specify theGoogle WorkspacemimeType when creating the file.

Note: If you're using the older Drive API v2, include theconvertquery parameter of theinsert method and specify the Google WorkspacemimeType 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 inGitHub. Learnhow tomigrate to Drive API v3.

Java

drive/snippets/drive_v3/src/main/java/UploadWithConversion.java
importcom.google.api.client.googleapis.json.GoogleJsonResponseException;importcom.google.api.client.http.FileContent;importcom.google.api.client.http.HttpRequestInitializer;importcom.google.api.client.http.javanet.NetHttpTransport;importcom.google.api.client.json.gson.GsonFactory;importcom.google.api.services.drive.Drive;importcom.google.api.services.drive.DriveScopes;importcom.google.api.services.drive.model.File;importcom.google.auth.http.HttpCredentialsAdapter;importcom.google.auth.oauth2.GoogleCredentials;importjava.io.IOException;importjava.util.Arrays;/* Class to demonstrate Drive's upload with conversion use-case. */publicclassUploadWithConversion{/**   * Upload file with conversion.   *   * @return Inserted file id if successful, {@code null} otherwise.   * @throws IOException if service account credentials file not found.   */publicstaticStringuploadWithConversion()throwsIOException{// Load pre-authorized user credentials from the environment.// TODO(developer) - See https://developers.google.com/identity for// guides on implementing OAuth2 for your application.GoogleCredentialscredentials=GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));HttpRequestInitializerrequestInitializer=newHttpCredentialsAdapter(credentials);// Build a new authorized API client service.Driveservice=newDrive.Builder(newNetHttpTransport(),GsonFactory.getDefaultInstance(),requestInitializer).setApplicationName("Drive samples").build();// File's metadata.FilefileMetadata=newFile();fileMetadata.setName("My Report");fileMetadata.setMimeType("application/vnd.google-apps.spreadsheet");java.io.FilefilePath=newjava.io.File("files/report.csv");FileContentmediaContent=newFileContent("text/csv",filePath);try{Filefile=service.files().create(fileMetadata,mediaContent).setFields("id").execute();System.out.println("File ID: "+file.getId());returnfile.getId();}catch(GoogleJsonResponseExceptione){// TODO(developer) - handle error appropriatelySystem.err.println("Unable to move file: "+e.getDetails());throwe;}}}

Python

drive/snippets/drive-v3/file_snippet/upload_with_conversion.py
importgoogle.authfromgoogleapiclient.discoveryimportbuildfromgoogleapiclient.errorsimportHttpErrorfromgoogleapiclient.httpimportMediaFileUploaddefupload_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 clientservice=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-memberfile=(service.files().create(body=file_metadata,media_body=media,fields="id").execute())print(f'File with ID: "{file.get("id")}" has been uploaded.')exceptHttpErroraserror:print(f"An error occurred:{error}")file=Nonereturnfile.get("id")if__name__=="__main__":upload_with_conversion()

Node.js

drive/snippets/drive_v3/file_snippets/upload_with_conversion.js
importfsfrom'node:fs';import{GoogleAuth}from'google-auth-library';import{google}from'googleapis';/** * Uploads a file to Google Drive and converts it to a Google Sheet. * @return {Promise<string|null|undefined>} The ID of the uploaded file. */asyncfunctionuploadWithConversion(){// Authenticate with Google and get an authorized client.// TODO (developer): Use an appropriate auth mechanism for your app.constauth=newGoogleAuth({scopes:'https://www.googleapis.com/auth/drive',});// Create a new Drive API client (v3).constservice=google.drive({version:'v3',auth});// The metadata for the file to be uploaded and converted.constfileMetadata={name:'My Report',// The MIME type to convert the file to.mimeType:'application/vnd.google-apps.spreadsheet',};// The media content to be uploaded.constmedia={mimeType:'text/csv',body:fs.createReadStream('files/report.csv'),};// Upload the file with conversion.constfile=awaitservice.files.create({requestBody:fileMetadata,media,fields:'id',});// Print the ID of the uploaded file.console.log('File Id:',file.data.id);returnfile.data.id;}

PHP

drive/snippets/drive_v3/src/DriveUploadWithConversion.php
<?phpuse 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
usingGoogle.Apis.Auth.OAuth2;usingGoogle.Apis.Drive.v3;usingGoogle.Apis.Services;namespaceDriveV3Snippets{// Class to demonstrate Drive's upload with conversion use-case.publicclassUploadWithConversion{/// <summary>/// Upload file with conversion./// </summary>/// <param name="filePath">Id of the spreadsheet file.</param>/// <returns>Inserted file id if successful, null otherwise.</returns>publicstaticstringDriveUploadWithConversion(stringfilePath){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. */GoogleCredentialcredential=GoogleCredential.GetApplicationDefault().CreateScoped(DriveService.Scope.Drive);// Create Drive API service.varservice=newDriveService(newBaseClientService.Initializer{HttpClientInitializer=credential,ApplicationName="Drive API Snippets"});// Upload file My Report on drive.varfileMetadata=newGoogle.Apis.Drive.v3.Data.File(){Name="My Report",MimeType="application/vnd.google-apps.spreadsheet"};FilesResource.CreateMediaUploadrequest;// Create a new drive.using(varstream=newFileStream(filePath,FileMode.Open)){// Create a new file, with metadata and stream.request=service.Files.Create(fileMetadata,stream,"text/csv");request.Fields="id";request.Upload();}varfile=request.ResponseBody;// Prints the uploaded file id.Console.WriteLine("File ID: "+file.Id);returnfile.Id;}catch(Exceptione){// TODO(developer) - handle error appropriatelyif(eisAggregateException){Console.WriteLine("Credential Not found");}elseif(eisFileNotFoundException){Console.WriteLine("File not found");}else{throw;}}returnnull;}}}

To see if a conversion is available, check theimportFormats field of theabout resource before creating the file. Supportedconversions are available dynamically in this array. Some common import formatsare:

FromTo
Microsoft Word, OpenDocument Text, HTML, RTF, plain textGoogle Docs
Microsoft Excel, OpenDocument Spreadsheet, CSV, TSV, plain textGoogle Sheets
Microsoft PowerPoint, OpenDocument PresentationGoogle Slides
JPEG, 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 anupdate request to aDocs, Sheets, or Slides file, thefull contents of the document are replaced.

When you convert an image to a Docs, Drive usesOptical Character Recognition (OCR) to convert the image to text. You canimprove the quality of the OCR algorithm by specifying the applicableBCP47 language code in theocrLanguage parameter.The extracted text appears in the document 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 thatcan be used to create, copy, and upload resources. For more information, seeGenerate IDs to use with your files.

You can safely retry uploads with pre-generated IDs if there's an indeterminateserver error or timeout. If the file action is successful, subsequent retriesreturn a409 Conflict HTTP status code response and duplicate files aren'tcreated.

Note that pre-generated IDs aren't supported for the creation ofGoogle Workspace files, except for theapplication/vnd.google-apps.drive-sdkandapplication/vnd.google-apps.folderMIMEtypes. Similarly, uploads referencing a conversionto a Google Workspace file format aren't supported.

Define indexable text for unknown file types

Users can use the Drive UI to find document content. You can alsouse thelist method on thefiles resource and thefullText field to search forcontent from your app. For more information, seeSearch for files andfolders.

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

For more information about indexable text, seeManage file metadata.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2026-01-20 UTC.