Uploading Files

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

You can send upload requests in any of the following ways:

  • Simple upload: uploadType=media. For quick transfer of a small file (5 MB or less). To perform a simple upload, refer to Performing 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 Performing 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 Performing 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.

Basic uploads

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);
    }
}];

Importing 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.

Uploading 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.

发送以下问题的反馈:

此网页
Drive REST API
Drive REST API