The Drive API allows you to upload file data when you create or update a File resource.
In this guide and reference, media refers to all available files with MIME types that we support for upload to Google Drive. For a list of some of the MIME types that begin with 'application/vnd.google-apps', see create. The user can upload any file they want to Drive and some MIME type will be set for the item. If the format of the content can't be detected, then the MIME type will be set to 'application/octet-stream'.
When you upload media, you use a special URI. Methods that support media uploads have two URI endpoints:
- The
/upload
URI, for the media. The format of the/upload
endpoint is the standard resource URI with an/upload
prefix. Use this URI when you transfer the media data itself. Example:POST /upload/drive/v2/files
. - The standard resource URI, for the metadata. If the resource contains any
data fields, those fields are used to store metadata that describes the uploaded
file. You can use this URI when you create or update metadata values.
Example:
POST /drive/v2/files
.
Upload types
There are three types of uploads you can perform:
Simple upload:
uploadType=media
. For quick transfer of a small file (5 MB or less). To perform a simple upload, refer to Perform a Simple Upload.Multipart upload:
uploadType=multipart
. For quick transfer of a small file (5 MB or less) and metadata that describes the file, all in a single request. To perform a multipart upload, refer to Perform a Multipart Upload.Resumable upload:
uploadType=resumable
. For more reliable transfer, especially important with large files. Resumable uploads are a good choice for most applications, since they also work for small files at the cost of one additional HTTP request per upload. To perform a resumable upload, refer to Perform a Resumable Upload.
Most Google API client libraries implement at least one of the methods. Refer to the client library documentation for additional details on how to use each of the methods.
Perform a simple upload
A simple upload is the most straightforward way to upload a file. Use this option if:
- the file is small enough to upload again in its entirety if the connection fails.
- there is no metadata to send or if you plan to send metadata in a separate request.
If you need to provide metadata for the file, you can use a multipart upload or resumable upload instead.
For larger files (more than 5 MB) or less reliable network connections, use the resumable upload.
These examples show how to upload an image using the client libraries:
Java
File fileMetadata = new File();
fileMetadata.setTitle("photo.jpg");
java.io.File filePath = new java.io.File("files/photo.jpg");
FileContent mediaContent = new FileContent("image/jpeg", filePath);
File file = driveService.files().insert(fileMetadata, mediaContent)
.setFields("id")
.execute();
System.out.println("File ID: " + file.getId());
Python
file_metadata = {'title': 'photo.jpg'}
media = MediaFileUpload('files/photo.jpg',
mimetype='image/jpeg')
file = drive_service.files().insert(body=file_metadata,
media_body=media,
fields='id').execute()
print 'File ID: %s' % file.get('id')
PHP
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'title' => 'photo.jpg'));
$content = file_get_contents('files/photo.jpg');
$file = $driveService->files->insert($fileMetadata, array(
'data' => $content,
'mimeType' => 'image/jpeg',
'uploadType' => 'multipart',
'fields' => 'id'));
printf("File ID: %s\n", $file->id);
.NET
var fileMetadata = new File()
{
Title = "photo.jpg"
};
FilesResource.InsertMediaUpload request;
using (var stream = new System.IO.FileStream("files/photo.jpg",
System.IO.FileMode.Open))
{
request = driveService.Files.Insert(
fileMetadata, stream, "image/jpeg");
request.Fields = "id";
request.Upload();
}
var file = request.ResponseBody;
Console.WriteLine("File ID: " + file.Id);
Ruby
file_metadata = {
title: 'photo.jpg'
}
file = drive_service.insert_file(file_metadata,
fields: 'id',
upload_source: 'files/photo.jpg',
content_type: 'image/jpeg')
puts "File Id: #{file.id}"
file_metadata = {}
file = drive_service.update_file(id,
file_metadata,
fields: 'id',
upload_source: 'files/photo.jpg',
content_type: 'image/jpeg')
puts "File Id: #{file.id}"
Node.js
var fileMetadata = {
'title': 'photo.jpg'
};
var media = {
mimeType: 'image/jpeg',
body: fs.createReadStream('files/photo.jpg')
};
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);
}
});
Send a simple upload request
To use simple upload:
- Create a
POST
request to the method's/upload
URI. To update an existing file, usePUT
. Add the query parameter
uploadType=media
.For example:
POST https://www.googleapis.com/upload/drive/v2/files?uploadType=media
Add the file's data to the request body.
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 heading is not required if you use chunked transfer encoding.
Send the request.
Example: Send a simple upload request
This example shows a simple upload request:
POST https://www.googleapis.com/upload/drive/v2/files?uploadType=media HTTP/1.1 Content-Type: image/jpeg Content-Length: [NUMBER_OF_BYTES_IN_FILE] Authorization: Bearer [YOUR_AUTH_TOKEN] [JPEG_DATA]
If the request succeeds, the server returns the HTTP 200 OK
status code along
with the file's metadata:
HTTP/1.1 200 Content-Type: application/json { "title": "Untitled" }
A blob uploaded to Drive gets "Untitled" as the default title. For information about how to handle errors, refer to Handle errors.
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.
If your file does not have any metadata, use simple upload instead. For larger files (more than 5 MB) or less reliable network connections, use resumable upload instead.
Send a multipart upload request
To use multipart upload:
- Create a
POST
request to the method's/upload
URI. To update an existing file, usePUT
. Add the query parameter
uploadType=multipart
.For example:
POST https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart
Create the body of the request. Format the body according to the
multipart/related
content type [RFC 2387], which contains two parts:- Metadata part. Must come first, and must have a
Content-Type
header set toapplication/json; charset=UTF-8
. Add the file's metadata to this part in JSON format. - Media part. Must come second, and must have a
Content-Type
header, which may have any MIME type. Add the file's data to this part.
Identify each part with a boundary string, preceded by two hyphens. In addition, add two hyphens after the final boundary string.
- Metadata part. Must come first, and must have a
Add these top-level HTTP headers:
Content-Type
. Set tomultipart/related
, and include the boundary string you're using to identify the different parts of the request. For example:Content-Type: multipart/related; boundary=foo_bar_baz
Content-Length
. Set to the total number of bytes in the request body.
Send the request.
Example: Send a multipart upload request
This example shows a multipart upload request:
POST https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart HTTP/1.1 Authorization: Bearer [YOUR_AUTH_TOKEN] Content-Type: multipart/related; boundary=foo_bar_baz Content-Length: [NUMBER_OF_BYTES_IN_ENTIRE_REQUEST_BODY] --foo_bar_baz Content-Type: application/json; charset=UTF-8 { "title": "myObject" } --foo_bar_baz Content-Type: image/jpeg [JPEG_DATA] --foo_bar_baz--
If the request succeeds, the server returns the HTTP 200 OK
status code along
with the file's metadata:
HTTP/1.1 200 Content-Type: application/json { "title": "myObject" }
To handle errors, refer to Handle errors.
Perform a resumable upload
This protocol allows you to resume an upload operation after a communication failure interrupts the flow of data. Use this option if:
- You transfer large files.
- The likelihood of a network interruption or some other transmission failure is high (for example, if you upload a file from a mobile app).
Resumable uploads can also reduce your bandwidth usage when there is a network failure, because you don't have to restart large file uploads from the start.
If you send small files over a reliable network connection, you can use simple upload or multipart upload instead.
Learn about request URIs
When you upload media, you use a special URI. In fact, methods that support media uploads have two URI endpoints:
- The
/upload
URI, for the media. The format of the/upload
endpoint is the standard resource URI with an/upload
prefix. Use this URI when you transfer the media data itself. Example:POST /upload/drive/v2/files
. - The standard resource URI, for the metadata. If the resource contains any
data fields, those fields store metadata that describes the uploaded
file. You can use this URI to create or update metadata values.
Example:
POST /drive/v2/files
.
Initiate a resumable upload session
To initiate a resumable upload session:
- Create a request to the method's
/upload
URI. To create a new file, usePOST
. To update an existing file, usePUT
. Add the query parameter
uploadType=resumable
.For example:
POST https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable
or:
PUT https://www.googleapis.com/upload/drive/v2/files/[FILE_ID]?uploadType=resumable
If you have metadata for the file, add the metadata to the request body in JSON format. Otherwise, leave the request body empty.
Add these HTTP headers:
X-Upload-Content-Type
. Optional. Set to the MIME type of the file data, which will be transferred in subsequent requests. If the MIME type of the data is not specified in metadata or through this header, the object will be served asapplication/octet-stream
.X-Upload-Content-Length
. Optional. Set to the number of bytes of file data, which will be transferred in subsequent requests.Content-Type
. Required if you have metadata for the file. Set toapplication/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.
Send the request.
Example: Initiate a resumable upload session
This example shows how to initiate a resumable session to upload a new file:
POST https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable HTTP/1.1 Authorization: Bearer [YOUR_AUTH_TOKEN] Content-Length: 38 Content-Type: application/json; charset=UTF-8 X-Upload-Content-Type: image/jpeg X-Upload-Content-Length: 2000000 { "title": "myObject" }
The next section describes how to handle the response.
Save the resumable session URI
If the session 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. Use the resumable session URI to upload the file data
and query the upload status.
Copy and save the resumable session URI so you can use it for subsequent requests.
Example: Save the resumable session URI
This example shows a response that includes a resumable session URI:
HTTP/1.1 200 OK Location: https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable&upload_id=xa298sd_sdlkj2 Content-Length: 0
Upload the file
There are two ways to upload a file with a resumable session:
- In a single request. This approach is usually best, since it requires fewer requests and thus has better performance.
- In multiple chunks. Use this approach if:
- You need to reduce the amount of data transferred in any single request. You might need to do this when there is a fixed time limit for individual requests, as is true for certain classes of Google App Engine requests.
- You need to provide a customized indicator to show the upload progress.
Single request
To upload the file in a single request:
- Create a
PUT
request to the resumable session URI. - Add the file's data to the request body.
- Add a
Content-Length
HTTP header, set to the number of bytes in the file. - Send the request.
If the upload request is interrupted, or if you receive a 5xx
response,
follow the procedure in Resume an interrupted upload.
Multiple chunks
To upload the file in multiple chunks:
- Create a
PUT
request to the resumable session URI. - 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.
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.
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.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
or201 Created
response, along with any metadata associated with the resource.
Example: Upload the file
Single request
This example shows a resumable request to upload an entire 2,000,000-byte JPEG file, and uses the resumable session URI obtained in the previous step:
PUT https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable&upload_id=xa298sd_sdlkj2 HTTP/1.1 Content-Length: 2000000 Content-Type: image/jpeg [BYTES 0-1999999]
If the request succeeds, you receive a 200 OK
or 201 Created
response,
along with any metadata associated with the resource.
Multiple chunks
This example shows a request that sends the first 524,288 bytes (512 KB) of the file, and uses the resumable session URI obtained in the previous step:
PUT https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable&upload_id=xa298sd_sdlkj2 HTTP/1.1 Content-Length: 524288 Content-Type: image/jpeg Content-Range: bytes 0-524287/2000000 [BYTES 0-524287]
If the request succeeds, the server responds with 308 Resume Incomplete
,
along with a Range
header that identifies the total number of bytes that
have been stored so far:
HTTP/1.1 308 Resume Incomplete Content-Length: 0 Range: bytes=0-524287
Use the upper value returned in the Range
header to determine where to
start the next chunk. Continue to PUT
each chunk of the file until the
entire file has been uploaded.
When the entire 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. To do this:
- To request the upload status, create an empty
PUT
request to the resumable session URI. 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*/*
.Send the request.
Process the response.
- A
200 OK
or201 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.
- A
If you received a
308 Resume Incomplete
response, process the response'sRange
header, which specifies which bytes the server has received so far. The response will not have aRange
header if no bytes have been received yet.For example, a
Range
header ofbytes=0-42
indicates that the first 43 bytes of the file have been received.Now that you know where to resume the upload, continue to upload the file, either send the data that remains or send the next chunk. 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.
Example: Resume an interrupted upload
This example shows a request for the upload status:
PUT https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable&upload_id=xa298sd_sdlkj2 HTTP/1.1 Content-Length: 0 Content-Range: bytes */2000000
The server's response uses the Range
header to indicate that it has received
the first 43 bytes of the file so far:
HTTP/1.1 308 Resume Incomplete Content-Length: 0 Range: bytes=0-42
You can then send a request to resume the upload. Send the bytes that remain in the file. Start at byte 43:
PUT https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable&upload_id=xa298sd_sdlkj2 HTTP/1.1 Content-Length: 1999957 Content-Range: bytes 43-1999999/2000000 [BYTES 43-1999999]
Handle errors
When you upload media, be sure to follow these best practices related to handle errors:
- Resume or retry uploads that fail due to connection interruptions or any 5xx
errors, for example:
- 500 Internal Server Error
- 502 Bad Gateway
- 503 Service Unavailable
- 504 Gateway Timeout
- Resume or retry uploads that fail due to 403 rate limit errors.
- Use an exponential backoff strategy if any 403 or 5xx server error is returned when upload requests retry or resend. These errors can occur if a server gets overloaded. Exponential backoff can help alleviate these kinds of problems when there is a high volume of requests or heavy network traffic.
- (Resumable uploads only) Restart uploads if a
404 Not Found
error is received after it resumes or uploads a chunk. This indicates the upload session has expired and must be restarted from the start. Upload sessions expire after 1 week of inactivity.
For additional details, see Handling API Errors.
Import to Google Docs types
When you create a file in Google Drive, you can convert some types file into a Google Docs, Sheets or Slides document. Include theconvert
query parameters and set the mimeType
property of the file.
This sample shows how to upload a CSV file as a spreadsheet:
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')
PHP
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'title' => 'My Report',
'mimeType' => 'application/vnd.google-apps.spreadsheet'));
$content = file_get_contents('files/report.csv');
$file = $driveService->files->insert($fileMetadata, array(
'data' => $content,
'mimeType' => 'text/csv',
'uploadType' => 'multipart',
'fields' => 'id'));
printf("File ID: %s\n", $file->id);
.NET
var fileMetadata = new File()
{
Title = "My Report",
MimeType = "application/vnd.google-apps.spreadsheet"
};
FilesResource.InsertMediaUpload request;
using (var stream = new System.IO.FileStream("files/report.csv",
System.IO.FileMode.Open))
{
request = driveService.Files.Insert(
fileMetadata, stream, "text/csv");
request.Fields = "id";
request.Upload();
}
var file = request.ResponseBody;
Console.WriteLine("File ID: " + file.Id);
Ruby
file_metadata = {
title: 'My Report',
mime_type: 'application/vnd.google-apps.spreadsheet'
}
file = drive_service.insert_file(file_metadata,
fields: 'id',
upload_source: 'files/report.csv',
content_type: 'text/csv')
puts "File Id: #{file.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);
}
});
The supported conversions are available dynamically in the
About resource's importFormats
array
and include:
From | To |
---|---|
Microsoft Word, OpenDocument Text, HTML, RTF, plain text | Google Docs |
Microsoft Excel, OpenDocument Spreadsheet, CSV, TSV, plain text | Google Sheets |
Microsoft Powerpoint, OpenDocument Presentation | Google Slides |
JPEG, PNG, GIF, BMP, PDF | Google Docs (embeds the image in a Doc) |
plain text (special MIME type), JSON | Google 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 will be replaced.
When you convert images you can improve the quality of the OCR algorithm. Specify the applicable BCP 47 language
code in the ocrLanguage
parameter. The extracted text will appear 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
that can be used to upload and create resources. Upload and file creation
requests can then include these pregenerated IDs. Set the id
fields
in the file metadata.
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, it does not create duplicate files.
Note: Pregenerated IDs are not supported for native Google Document creation, or uploads where conversion to native Google Document format is requested.