Upload files

The Drive API allows you to upload file data when creating or updating a File resource.

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 transferring the media data itself. Example: POST /upload/drive/v3/files.
  • The standard resource URI, for the metadata. If the resource contains any data fields, those fields are used to store metadata describing the uploaded file. You can use this URI when creating or updating metadata values. Example: POST /drive/v3/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 describing 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 method for uploading 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. This might be true if you plan to send metadata for the file in a separate request, or if no metadata is available.

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.

The following examples show how to upload an image using the client libraries:

Java

File fileMetadata = new File();
fileMetadata.setName("photo.jpg");
java.io.File filePath = new java.io.File("files/photo.jpg");
FileContent mediaContent = new FileContent("image/jpeg", filePath);
File file = driveService.files().create(fileMetadata, mediaContent)
    .setFields("id")
    .execute();
System.out.println("File ID: " + file.getId());

Python

file_metadata = {'name': 'photo.jpg'}
media = MediaFileUpload('files/photo.jpg',
                        mimetype='image/jpeg')
file = drive_service.files().create(body=file_metadata,
                                    media_body=media,
                                    fields='id').execute()
print 'File ID: %s' % file.get('id')

PHP

$fileMetadata = new Google_Service_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);

.NET

var fileMetadata = new File()
{
    Name = "photo.jpg"
};
FilesResource.CreateMediaUpload request;
using (var stream = new System.IO.FileStream("files/photo.jpg",
                        System.IO.FileMode.Open))
{
    request = driveService.Files.Create(
        fileMetadata, stream, "image/jpeg");
    request.Fields = "id";
    request.Upload();
}
var file = request.ResponseBody;
Console.WriteLine("File ID: " + file.Id);

Ruby

file_metadata = {
    name: 'photo.jpg'
}
file = drive_service.create_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 = {
  'name': 'photo.jpg'
};
var media = {
  mimeType: 'image/jpeg',
  body: fs.createReadStream('files/photo.jpg')
};
drive.files.create({
  resource: fileMetadata,
  media: media,
  fields: 'id'
}, function (err, file) {
  if (err) {
    // Handle error
    console.error(err);
  } else {
    console.log('File Id: ', file.id);
  }
});

Objective-C

NSData *fileData = [[NSFileManager defaultManager] contentsAtPath:@"files/photo.jpg"];

GTLRDrive_File *metadata = [GTLRDrive_File object];
metadata.name = @"photo.jpg";

GTLRUploadParameters *uploadParameters = [GTLRUploadParameters uploadParametersWithData:fileData
                                                                               MIMEType:@"image/jpeg"];
uploadParameters.shouldUploadWithSingleRequest = TRUE;
GTLRDriveQuery_FilesCreate *query = [GTLRDriveQuery_FilesCreate queryWithObject:metadata
                                                               uploadParameters:uploadParameters];
query.fields = @"id";
[driveService executeQuery:query completionHandler:^(GTLRServiceTicket *ticket,
                                                     GTLRDrive_File *file,
                                                     NSError *error) {
    if (error == nil) {
        NSLog(@"File ID %@", file.identifier);
    } else {
        NSLog(@"An error occurred: %@", error);
    }
}];

Send a simple upload request

To use simple upload:

  1. Create a POST request to the method's /upload URI. To update an existing file, use PUT.
  2. Add the query parameter uploadType=media.

    For example:

    POST https://www.googleapis.com/upload/drive/v3/files?uploadType=media
  3. Add the file's data to the request body.

  4. Add the following HTTP headers:

    • Content-Type. Set to the MIME media type of the object being uploaded.
    • Content-Length. Set to the number of bytes you are uploading. This heading is not required if you are using chunked transfer encoding.
  5. Send the request.

Example: Send a simple upload request

The following example shows a simple upload request:

POST https://www.googleapis.com/upload/drive/v3/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

{
  "name": "myObject"
}

For information on error handling, 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 are sending is small enough to upload again in its entirety if the connection fails.

If your file does not have any metadata, use [simple upload][#simple] instead. For larger files (more than 5 MB) or less reliable network connections, use [resumable upload][#resumable] instead.

Send a multipart upload request

To use multipart upload:

  1. Create a POST request to the method's /upload URI. To update an existing file, use PUT.
  2. Add the query parameter uploadType=multipart.

    For example:

    POST https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart
  3. Create the body of the request. Format the body according to the multipart/related content type [RFC 2387], which contains two parts:

    1. Metadata part. Must come first, and must have a Content-Type header set to application/json; charset=UTF-8. Add the file's metadata to this part in JSON format.
    2. 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.

  4. Add the following top-level HTTP headers:

    • Content-Type. Set to multipart/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.
  5. Send the request.

Example: Send a multipart upload request

The following example shows a multipart upload request:

POST https://www.googleapis.com/upload/drive/v3/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

{
  "name": "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

{
  "name": "myObject"
}

For information on error handling, 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 are transferring large files.
  • The likelihood of a network interruption or some other transmission failure is high (for example, if you are uploading 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 beginning.

If you are sending small files over a reliable network connection, you can use [simple upload][#simple] or [multipart upload][#multipart] 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 transferring the media data itself. Example: POST /upload/drive/v3/files.
  • The standard resource URI, for the metadata. If the resource contains any data fields, those fields are used to store metadata describing the uploaded file. You can use this URI when creating or updating metadata values. Example: POST /drive/v3/files.

Initiate a resumable upload session

To initiate a resumable upload session:

  1. Create a request to the method's /upload URI. To create a new file, use POST. To update an existing file, use PUT.
  2. Add the query parameter uploadType=resumable.

    For example:

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

    or:

    PUT https://www.googleapis.com/upload/drive/v3/files/[FILE_ID]?uploadType=resumable
  3. If you have metadata for the file, add the metadata to the request body in JSON format. Otherwise, leave the request body empty.

  4. Add the following 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 as application/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 to application/json; charset=UTF-8.
    • Content-Length. Required unless you are using chunked transfer encoding. Set to the number of bytes in the body of this initial request.
  5. Send the request.

Example: Initiate a resumable upload session

The following example shows how to initiate a resumable session to upload a new file:

POST https://www.googleapis.com/upload/drive/v3/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

{
  "name": "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

The following example shows a response that includes a 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

Upload the file

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

  1. In a single request. This approach is usually best, since it requires fewer requests and thus has better performance.
  2. 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 showing the upload progress.

Single request

To upload the file in a 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.

Multiple chunks

To upload the file in multiple chunks:

  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 the following 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 are uploading. For example, Content-Range: bytes 0-524287/2000000 shows that you are uploading 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 remaining chunk 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.

Example: Upload the file

Single request

The following example shows a resumable request to upload an entire 2,000,000-byte JPEG file, using the resumable session URI obtained in the previous step:

PUT https://www.googleapis.com/upload/drive/v3/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

The following example shows a request that sends the first 524,288 bytes (512 KB) of the file, using the resumable session URI obtained in the previous step:

PUT https://www.googleapis.com/upload/drive/v3/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 receiving a response, or if you receive a 503 Service Unavailable response, then you need to resume the interrupted upload. To do this:

  1. To request the upload status, create an empty PUT request to the resumable session URI.
  2. Add a Content-Range header indicating 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 uploading the file.
    • A 404 Not Found response indicates the upload session has expired and the upload needs to be restarted from the beginning.
  5. If you received a 308 Resume Incomplete response, process the response's Range header, which specifies which bytes the server has received so far. The response will not have a Range header if no bytes have been received yet.

    For example, a Range header of bytes=0-42 indicates that the first 43 bytes of the file have been received.

  6. Now that you know where to resume the upload, continue uploading the file, either by sending the remaining data or by sending the next chunk. Include a Content-Range header indicating which portion of the file you are sending.

    For example, Content-Range: bytes 43-1999999/2000000 indicates that you are sending bytes 43 through 1,999,999.

Example: Resume an interrupted upload

The following example shows a request for the upload status:

PUT https://www.googleapis.com/upload/drive/v3/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 by sending the remaining bytes of the file, starting at byte 43:

PUT https://www.googleapis.com/upload/drive/v3/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 uploading media, be sure to follow these best practices related to error handling:

  • Resume or retry uploads that fail due to connection interruptions or any 5xx errors, including:
    • 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 resuming or retrying upload requests. These errors can occur if a server is getting 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 attempting to resume or upload a chunk. This indicates the upload session has expired and must be restarted from the beginning. Upload sessions expire after 1 week of inactivity.

For additional details, see Handling API Errors.

Import to Google Docs types

When creating a file in Google Drive, you can convert some types file into a Google Docs, Sheets or Slides document by specifying the mimeType property of the file. The following sample shows how to upload a CSV file as a spreadsheet:

Java

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

Python

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

PHP

$fileMetadata = new Google_Service_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);

.NET

var fileMetadata = new File()
{
    Name = "My Report",
    MimeType = "application/vnd.google-apps.spreadsheet"
};
FilesResource.CreateMediaUpload request;
using (var stream = new System.IO.FileStream("files/report.csv",
                        System.IO.FileMode.Open))
{
    request = driveService.Files.Create(
        fileMetadata, stream, "text/csv");
    request.Fields = "id";
    request.Upload();
}
var file = request.ResponseBody;
Console.WriteLine("File ID: " + file.Id);

Ruby

file_metadata = {
    name: 'My Report',
    mime_type: 'application/vnd.google-apps.spreadsheet'
}
file = drive_service.create_file(file_metadata,
                                 fields: 'id',
                                 upload_source: 'files/report.csv',
                                 content_type: 'text/csv')
puts "File Id: #{file.id}"

Node.js

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

Objective-C

NSData *fileData = [[NSFileManager defaultManager] contentsAtPath:@"files/report.csv"];

GTLRDrive_File *metadata = [GTLRDrive_File object];
metadata.name = @"My Report";
metadata.mimeType = @"application/vnd.google-apps.spreadsheet";

GTLRUploadParameters *uploadParameters = [GTLRUploadParameters uploadParametersWithData:fileData
                                                                               MIMEType:@"text/csv"];
uploadParameters.shouldUploadWithSingleRequest = TRUE;
GTLRDriveQuery_FilesCreate *query = [GTLRDriveQuery_FilesCreate queryWithObject:metadata
                                                               uploadParameters:uploadParameters];
query.fields = @"id";
[driveService executeQuery:query completionHandler:^(GTLRServiceTicket *ticket,
                                                     GTLRDrive_File *file,
                                                     NSError *error) {
    if (error == nil) {
        NSLog(@"File ID %@", file.identifier);
    } else {
        NSLog(@"An error occurred: %@", error);
    }
}];

The supported conversions are available dynamically in the About resource's importFormats array and include:

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 uploading and converting media during an update request to a Google Doc, Sheet, or Slide the full contents of the document will be replaced.

When converting images you can improve the quality of the OCR algorithm by specifying the applicable BCP 47 language code in the ocrLanguage parameter. The extracted text will appear in the Google Docs document alongside the embedded image.

Upload using a pregenerated ID

The Drive API allows you to retrieve a list of pregenerated file IDs that can be used for uploading and creating resources. Upload and file creation requests can then include these pregenerated IDs by setting 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 instead of creating duplicate files.

Note: Pregenerated IDs are not supported for native Google Document creation, or uploads where conversion to native Google Document format is requested.

傳送您對下列選項的寶貴意見...

這個網頁
Drive REST API
Drive REST API
需要協助嗎?請前往我們的支援網頁