Upload file data

The Drive API allows you to upload file data when you create or update a File.

There are three types of uploads you can perform:

  • Simple upload (uploadType=media). Use this upload type to quickly 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 (uploadType=multipart). Use this upload type to quickly transfer a small file (5 MB or less) and metadata that describes the file, in a single request. To perform a multipart upload, refer to Perform a multipart upload.

  • Resumable upload (uploadType=resumable). 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 the types of uploads. Refer to the client library documentation for additional details on how to use each of the types.

Perform a simple upload

To perform a simple upload, use the files.insert method with uploadType=media.

The following shows how to perform a simple upload:

HTTP

  1. Create a POST request to the method's /upload URI with the query parameter of uploadType=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 being uploaded.
    • Content-Length. Set to the number of bytes you upload. This header is not required if you use chunked transfer encoding.
  4. Send the request. If the request succeeds, the server returns the HTTP 200 OK status code along with the file's metadata.

When you perform a simple upload, basic metadata is created and some attributes are inferred from the file, such as the MIME type or modifiedTime. 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 allows you to send metadata along with the data to upload. 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.insert method with uploadType=multipart.

When creating files, files should specify a file extension in the file's name field. For example, when creating a photo JPEG file, you might specify something like "name": "photo.jpg" in the metadata. Subsequent calls to files.get return the read-only fileExtension property containing the extension originally specified in the name field.

Perform a resumable upload

A resumable upload allows you to 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 is a network failure.

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

A resumable upload consists of three 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 upload is disturbed, resume the upload.

Send the initial request

To initiate a resumable upload, use the files.insert method with uploadType=resumable.

HTTP

  1. Create a POST request to the method's /upload URI with the query parameter of uploadType=resumable:

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

    If the initiation request succeeds, the response includes a 200 OK HTTP status code. In addition, it includes a Location 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
    

    You should 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.

  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:

    • X-Upload-Content-Type. 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 metadata or through this header, the object is served as application/octet-stream.
    • X-Upload-Content-Length. Optional. Set to the number of bytes of file data, which is transferred in subsequent requests.
    • Content-Type. Required if you have metadata for the file. Set to application/json; charset=UTF-8.
    • Content-Length. 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 200 OK HTTP status code. In addition, the response includes a Location 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 [Uploading content](#uploading}

Upload the content

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

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

HTTP - single request

  1. Create a PUT 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 5xx response, follow the procedure in Resume an interrupted upload.

HTTP - multiple requests

  1. Create a PUT 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:

    • Content-Length. Set to the number of bytes in the current chunk.
    • Content-Range. Set to show which bytes in the file you upload. For example, Content-Range: bytes 0-524287/2000000 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 5xx 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 Range header in the response to determine where to start the next chunk. Do not assume that the server received all bytes sent in the previous request.

When the entire file upload is complete, you receive a 200 OK or 201 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 a 503 Service Unavailable response, then you need to resume the interrupted upload.

HTTP

  1. To request the upload status, create an empty PUT request to the resumable session URI.

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

  3. Send the request.

  4. Process the response:

    • A 200 OK or 201 Created response indicates that the upload was completed, and no further action is necessary.
    • A 308 Resume Incomplete response indicates that you need to continue to upload the file.
    • A 404 Not Found response indicates the upload session has expired and the upload needs to be restarted from the start.
  5. If you received a 308 Resume Incomplete response, process the response's Range header, to determine which bytes the server has received. If the response doesn't have a Range header, no bytes have been received. For example, a Range header of bytes=0-42 indicates that the first 43 bytes of the file have been received and that the next chunk to upload would start with byte 43.

  6. Now that you know where to resume the upload, continue to upload the file beginning with the next byte. Include a Content-Range header to indicate which portion of the file you send. For example, Content-Range: bytes 43-1999999/2000000 indicates that you send bytes 43 through 1,999,999.

Handle media upload errors

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

  • For 5xx errors, resume or retry uploads that fail due to connection interruptions. For further information on handling 5xx errors, refer to Resolve errors
  • For 403 rate limit errors, resume or retry uploads. For further information on handling 403 rate limit errors, refer to Resolve a 403 error: Rate limit exceeded
  • For 404 "Not Found" errors (resumable uploads only), restart the upload. This error indicates the upload session has expired and must be restarted from the start. Upload sessions expire after 1 week of inactivity.

Import to Google Docs types

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

To convert a file to a specific G Suite file type, include the convert query parameters and specify the G Suite mimeType when creating the file. The following shows how to convert a CSV file to a G Suite sheet:

Java

File fileMetadata = new File();
fileMetadata.setTitle("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);
File file = driveService.files().insert(fileMetadata, mediaContent)
    .setFields("id")
    .execute();
System.out.println("File ID: " + file.getId());

Python

file_metadata = {
    'title': 'My Report',
    'mimeType': 'application/vnd.google-apps.spreadsheet'
}
media = MediaFileUpload('files/report.csv',
                        mimetype='text/csv',
                        resumable=True)
file = drive_service.files().insert(body=file_metadata,
                                    media_body=media,
                                    fields='id').execute()
print 'File ID: %s' % file.get('id')

Node.js

var fileMetadata = {
  'title': 'My Report',
  'mimeType': 'application/vnd.google-apps.spreadsheet'
};
var media = {
  mimeType: 'text/csv',
  body: fs.createReadStream('files/report.csv')
};
drive.files.insert({
  resource: fileMetadata,
  media: media,
  fields: 'id'
}, function (err, file) {
  if (err) {
    // Handle error
    console.error(err);
  } else {
    console.log('File Id:', file.id);
  }
});

To see if a conversion is available, check the About resource's importFormats array prior to creating the file. Supported conversions are available dynamically in this array. Some common import formats are:

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 an update request to a Google Doc, Sheet, or Slide, the full contents of the document are replaced.

When you convert an image to a Google 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 ocrLanguage parameter. The extracted text appears in the Google Docs document alongside the embedded image.

Use a pregenerated ID to upload files

The Drive API allows you to retrieve a list of pregenerated file IDs used to upload and create resources. Upload and file creation requests can use these pregenerated IDs. Set the id field in the file metadata.

To create pregenerated IDs, call file.generateIds with the number of IDs to create.

You can safely retry uploads with pregenerated IDs in the case of an indeterminate server error or timeout. If the file was successfully created, subsequent retries return a HTTP 409 error, they do not create duplicate files.

Define indexable text for unknown file types

Users can use the Drive UI to search for document content. You can also use the file.list and the fullText field to search for content from your app. For further information on searching for files, refer to Search for files and folders

To allow content searches, Drive automatically indexes document contents when it recognizes the file type. Recognized file types include text documents, PDFs, images with text, and other common types. If your app saves files that Drive doesn't recognize, you should include text in the contentHints.indexableText field of the file. When specifying indexableText, keep in mind:

  • Ensure you capture key terms and concepts that you expect a user to search for.
  • The size limit for contentHints.indexableText is 128KiB.
  • You do not need to order the text in order of importance; the indexer determines importance.
  • Indexable text should be updated by your application with each save.
  • Ensure any indexableText actually appears in the contents or metadata of the file. Don't try to force a file to appear in search results by including terms that don't appear in the contents or metadata. Users don't like to perform searches that result in files containing irrelevant content.