上传文件数据

借助 Google Drive API,您可以在创建或更新 File 时上传文件数据。如需了解如何创建仅包含元数据的文件(例如文件夹),请参阅创建仅包含元数据的文件

您可以执行以下三种类型的上传:

  • 简单上传 (uploadType=media):使用此上传类型可在不提供元数据的情况下传输小媒体文件(5 MB 或更小)。如需执行简单上传,请参阅执行简单上传

  • 多部分上传 (uploadType=multipart):使用此上传类型可在单个请求中传输小文件(5 MB 或更小)以及描述该文件的元数据。如需执行多部分上传,请参阅执行多部分上传

  • 可续传上传 (uploadType=resumable):此上传类型适用于大文件(大于 5 MB)以及网络中断的可能性较高时(例如通过移动应用创建文件时)。对于大多数应用而言,可续传上传也是不错的选择,因为这类上传方式也适合小型文件,而且每次上传时只需多发出一个 HTTP 请求。如需执行可续传上传,请参阅执行可续传上传

Google API 客户端库至少可实现以下上传类型中的一种。请参阅客户端库文档,详细了解如何使用每种类型。

使用 PATCHPUT

我们回顾一下,HTTP 动词 PATCH 支持部分文件资源更新,而 HTTP 动词 PUT 则支持完全资源替换。请注意,在向现有资源添加新字段时,PUT 可能会引入破坏性更改。

上传文件资源时,请遵循以下准则:

  • 对于可续传上传的初始请求,或针对简单上传或多部分上传的唯一请求,请使用 API 参考文档中记录的 HTTP 动词。
  • 请求开始后,对可续传上传的所有后续请求使用 PUT。无论调用什么方法,这些请求都会上传内容。

执行简单上传

如需执行简单上传,请将 files.create 方法与 uploadType=media 结合使用。

下面介绍了如何执行简单上传:

HTTP

  1. 使用 uploadType=media 查询参数创建对方法的 /upload URI 的 POST 请求:

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

  2. 将文件的数据添加到请求正文。

  3. 添加以下 HTTP 标头:

    • Content-Type。请将此项设为要上传的对象的 MIME 媒体类型。
    • Content-Length。请将此项设为您上传的字节数。如果您使用分块传输编码,则此标头并非必需。
  4. 发送请求。如果请求成功,服务器将返回 HTTP 200 OK 状态代码以及文件的元数据。{HTTP}

当您执行简单上传时,系统会创建基本元数据,并根据文件推断某些属性,例如 MIME 类型或 modifiedTime。如果您的文件较小且文件元数据不重要,则可以使用简单上传。

执行多部分上传

借助多部分上传请求,您可以在同一请求中上传元数据和数据。如果您发送的数据非常小,在连接失败时需要再次上传整个数据,则可以使用此选项。

如需执行多部分上传,请将 files.create 方法与 uploadType=multipart 结合使用。

下面展示了如何执行多部分上传:

Java

drive/snippets/drive_v3/src/main/java/UploadBasic.java
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Arrays;

/* Class to demonstrate use of Drive insert file API */
public class UploadBasic {

  /**
   * Upload new file.
   *
   * @return Inserted file metadata if successful, {@code null} otherwise.
   * @throws IOException if service account credentials file not found.
   */
  public static String uploadBasic() throws IOException {
    // Load pre-authorized user credentials from the environment.
    // TODO(developer) - See https://developers.google.com/identity for
    // guides on implementing OAuth2 for your application.
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
        .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
        credentials);

    // Build a new authorized API client service.
    Drive service = new Drive.Builder(new NetHttpTransport(),
        GsonFactory.getDefaultInstance(),
        requestInitializer)
        .setApplicationName("Drive samples")
        .build();
    // Upload file photo.jpg on drive.
    File fileMetadata = new File();
    fileMetadata.setName("photo.jpg");
    // File's content.
    java.io.File filePath = new java.io.File("files/photo.jpg");
    // Specify media type and file-path for file.
    FileContent mediaContent = new FileContent("image/jpeg", filePath);
    try {
      File file = service.files().create(fileMetadata, mediaContent)
          .setFields("id")
          .execute();
      System.out.println("File ID: " + file.getId());
      return file.getId();
    } catch (GoogleJsonResponseException e) {
      // TODO(developer) - handle error appropriately
      System.err.println("Unable to upload file: " + e.getDetails());
      throw e;
    }
  }
}

Python

drive/snippets/drive-v3/file_snippet/upload_basic.py
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_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 client
    service = build("drive", "v3", credentials=creds)

    file_metadata = {"name": "download.jpeg"}
    media = MediaFileUpload("download.jpeg", mimetype="image/jpeg")
    # pylint: disable=maybe-no-member
    file = (
        service.files()
        .create(body=file_metadata, media_body=media, fields="id")
        .execute()
    )
    print(f'File ID: {file.get("id")}')

  except HttpError as error:
    print(f"An error occurred: {error}")
    file = None

  return file.get("id")


if __name__ == "__main__":
  upload_basic()

Node.js

drive/snippets/drive_v3/file_snippets/upload_basic.js
/**
 * Insert new file.
 * @return{obj} file Id
 * */
async function uploadBasic() {
  const fs = require('fs');
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});
  const requestBody = {
    name: 'photo.jpg',
    fields: 'id',
  };
  const media = {
    mimeType: 'image/jpeg',
    body: fs.createReadStream('files/photo.jpg'),
  };
  try {
    const file = await service.files.create({
      requestBody,
      media: media,
    });
    console.log('File Id:', file.data.id);
    return file.data.id;
  } catch (err) {
    // TODO(developer) - Handle error
    throw err;
  }
}

PHP

drive/snippets/drive_v3/src/DriveUploadBasic.php
use Google\Client;
use Google\Service\Drive;
# TODO - PHP client currently chokes on fetching start page token
function 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
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;

namespace DriveV3Snippets
{
    // Class to demonstrate use of Drive insert file API
    public class UploadBasic
    {
        /// <summary>
        /// Upload new file.
        /// </summary>
        /// <param name="filePath">Image path to upload.</param>
        /// <returns>Inserted file metadata if successful, null otherwise.</returns>
        public static string DriveUploadBasic(string filePath)
        {
            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. */
                GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                    .CreateScoped(DriveService.Scope.Drive);

                // Create Drive API service.
                var service = new DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Drive API Snippets"
                });

                // Upload file photo.jpg on drive.
                var fileMetadata = new Google.Apis.Drive.v3.Data.File()
                {
                    Name = "photo.jpg"
                };
                FilesResource.CreateMediaUpload request;
                // Create a new file on drive.
                using (var stream = new FileStream(filePath,
                           FileMode.Open))
                {
                    // Create a new file, with metadata and stream.
                    request = service.Files.Create(
                        fileMetadata, stream, "image/jpeg");
                    request.Fields = "id";
                    request.Upload();
                }

                var file = request.ResponseBody;
                // Prints the uploaded file id.
                Console.WriteLine("File ID: " + file.Id);
                return file.Id;
            }
            catch (Exception e)
            {
                // TODO(developer) - handle error appropriately
                if (e is AggregateException)
                {
                    Console.WriteLine("Credential Not found");
                }
                else if (e is FileNotFoundException)
                {
                    Console.WriteLine("File not found");
                }
                else
                {
                    throw;
                }
            }
            return null;
        }
    }
}

HTTP

  1. 使用 uploadType=multipart 查询参数创建对方法的 /upload URI 的 POST 请求:

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

  2. 创建请求的正文。根据多部分/相关内容类型 RFC 2387 设置正文格式,该 RFC 2387 包含两个部分:

    • 元数据。元数据必须位于开头,并且必须将 Content-Type 标头设置为 application/json; charset=UTF-8。以 JSON 格式添加文件的元数据。
    • 媒体。媒体必须位于第二,并且必须具有任意 MIME 类型的 Content-Type 标头。将文件的数据添加到媒体部分。

    用边界字符串标识每个部分,并在前面加上两个连字符。此外,请在最后的定界字符串后添加两个连字符。

  3. 添加以下顶级 HTTP 标头:

    • Content-Type。设置为 multipart/related 并添加用于标识请求不同部分的边界字符串。例如:Content-Type: multipart/related; boundary=foo_bar_baz
    • Content-Length。请将此项设为请求正文包含的字节总数。
  4. 发送请求。

如果仅创建或更新元数据部分,而不包含关联数据,请向标准资源端点发送 POSTPATCH 请求:https://www.googleapis.com/drive/v3/files。如果请求成功,服务器将返回 HTTP 200 OK 状态代码以及文件的元数据。

创建文件时,他们应在文件的 name 字段中指定文件扩展名。例如,在创建照片 JPEG 文件时,您可以在元数据中指定类似于 "name": "photo.jpg" 的内容。对 files.get 的后续调用会返回只读 fileExtension 属性,该属性包含最初在 name 字段中指定的扩展名。

执行可续传上传

借助可续传上传,您可以在通信失败打断数据流后恢复上传操作。由于您不必从头开始重新上传大型文件,因此如果发生网络故障,可续传上传也可以减少带宽用量。

如果文件大小可能有很大差异,或者请求有固定的时间限制(例如移动操作系统后台任务和某些 App Engine 请求),可续传上传非常有用。如果您希望显示上传进度条,也可以使用可续传上传。

可续传上传包含以下几个高级步骤:

  1. 发送初始请求并检索可续传会话 URI。
  2. 上传数据并监控上传状态。
  3. (可选)如果上传受到干扰,请恢复上传。

发送初始请求

如需启动可续传上传,请将 files.create 方法与 uploadType=resumable 结合使用。

HTTP

  1. 使用 uploadType=resumable 查询参数创建对方法的 /upload URI 的 POST 请求:

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

    如果启动请求成功,响应将包含 200 OK HTTP 状态代码。此外,它还包含一个 Location 标头,用于指定可续传会话 URI:

    HTTP/1.1 200 OK
    Location: https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&upload_id=xa298sd_sdlkj2
    Content-Length: 0
    

    保存可续传会话 URI,以便上传文件数据并查询上传状态。可续传会话 URI 的有效期为一周。

  2. 如果您有文件的元数据,请将元数据以 JSON 格式添加到请求正文中。否则,请将请求正文留空。

  3. 添加以下 HTTP 标头:

    • X-Upload-Content-Type。可选。设置为后续请求中传输的文件数据的 MIME 类型。如果数据的 MIME 类型未在元数据中或通过此标头指定,系统会以 application/octet-stream. 的形式传送对象
    • X-Upload-Content-Length。可选。请将此项设为在后续请求中传输的文件数据的字节数。
    • Content-Type。如果您有文件的元数据,则需要添加此标头。设置为 application/json; charset=UTF-8
    • Content-Length。必需(除非您使用分块传输编码)。设置为此初始请求的正文中的字节数。
  4. 发送请求。如果会话启动请求成功,响应将包含 200 OK HTTP 状态代码。此外,响应还包含一个 Location 标头,该标头指定可续传会话 URI。使用可续传会话 URI 上传文件数据并查询上传状态。可续传会话 URI 的有效期为一周。

  5. 复制并保存可续传会话网址。

  6. 继续上传内容

上传内容

借助以下两种方法,您可以使用可续传会话上传文件:

  • 在单个请求中上传内容:如果可以通过一个请求上传文件,并且任何单个请求都没有固定的时间限制,或者您不需要显示上传进度指示器,则可以使用此方法。此方法是最佳方法,因为它需要的请求更少,并且可以提高性能。
  • 分多个分块上传内容:如果您必须减少任何单个请求中传输的数据量,请使用此方法。如果单个请求有固定的时间限制,您可能需要减少传输的数据,某些类别的 App Engine 请求就是如此。如果您必须提供自定义指示器以显示上传进度,此方法也很有用。

HTTP - 单一请求

  1. 创建一个针对可续传会话 URI 的 PUT 请求。
  2. 将文件的数据添加到请求正文。
  3. 添加 Content-Length HTTP 标头,并将其设置为文件中的字节数。
  4. 发送请求。如果上传请求中断,或者您收到 5xx 响应,请按照恢复中断的上传中的步骤操作。

HTTP - 多个请求

  1. 创建一个针对可续传会话 URI 的 PUT 请求。

  2. 将数据块的数据添加到请求正文。除了上传序列中的最后一个分块之外,您还可以创建大小为 256 KB(256 x 1024 字节)的倍数的分块。请尽量使用较大的数据块,以便高效地上传。

  3. 添加以下 HTTP 标头:

    • Content-Length。设置为当前数据块中的字节数。
    • Content-Range。请设置此项来指明要上传目标文件中的哪些字节。例如,Content-Range: bytes 0-524287/2000000 表示您上传某个 200 万字节文件中的前 524288 个字节 (256 x 1024 x 2)。
  4. 发送请求并处理响应。如果上传请求中断,或者您收到 5xx 响应,请按照恢复中断的上传中的步骤操作。

  5. 对文件中剩余的每个分块重复执行第 1 步到第 4 步。使用响应中的 Range 标头来确定从何处开始上传下一个分块。不要假定服务器已收到上一个请求中发送的所有字节。

当整个文件上传完毕后,您会收到 200 OK201 Created 响应,以及与资源关联的所有元数据。

恢复中断的上传

如果上传请求在响应前终止,或者您收到 503 Service Unavailable 响应,则必须恢复中断的上传。

HTTP

  1. 如需查询上传状态,请创建一个针对可续传会话 URI 的空 PUT 请求。

  2. 添加 Content-Range 标头,指示文件中的当前位置未知。例如,如果您的文件总长度为 200 万字节,请将 Content-Range 设为 */2000000。如果您不知道文件的完整大小,请将 Content-Range 设为 */*

  3. 发送请求。

  4. 处理响应:

    • 200 OK201 Created 响应表明上传已完成,无需执行进一步操作。
    • 308 Resume Incomplete 响应表示您必须继续上传文件。
    • 404 Not Found 响应表示上传会话已过期,必须从头开始重新上传。
  5. 如果您收到 308 Resume Incomplete 响应,请处理该响应的 Range 标头,以确定服务器已收到哪些字节。如果响应没有 Range 标头,则表示未收到任何字节。例如,如果 Range 标头为 bytes=0-42,则表示已收到文件的前 43 个字节,并且要上传的下一个分块将以字节 44 开头。

  6. 现在,您已知道应从何处恢复上传,接下来从下一个字节开始继续上传文件。添加 Content-Range 标头来指明您要发送文件的哪一部分。例如,Content-Range: bytes 43-1999999 表示您要发送第 44 字节到第 2,000,000 个字节。

处理媒体上传错误

上传媒体内容时,请遵循以下最佳实践来处理错误:

  • 对于 5xx 错误,请恢复或重试由于连接中断而失败的上传。如需详细了解如何处理 5xx 错误,请参阅 500、502、503、504 错误
  • 如果发生错误 403 rate limit,请重新尝试上传。如需详细了解如何处理 403 rate limit 错误,请参阅 403 错误:rateLimitExceeded
  • 如果执行可续传上传期间出现任何 4xx 错误(包括 403),请重新开始上传。这些错误表示上传会话已过期,必须通过请求新的会话 URI 重新启动。上传会话也会在处于非活动状态一周后过期。

导入到 Google 文档类型

在云端硬盘中创建文件时,您可能希望将文件转换为 Google Workspace 文件类型,例如 Google 文档或表格。例如,您可能希望将文档从您喜爱的文字处理器转换为文档,以充分利用其功能。

如需将文件转换为特定的 Google Workspace 文件类型,请在创建文件时指定 Google Workspace mimeType

下面介绍了如何将 CSV 文件转换为 Google Workspace 表格:

Java

drive/snippets/drive_v3/src/main/java/UploadWithConversion.java
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Arrays;

/* Class to demonstrate Drive's upload with conversion use-case. */
public class UploadWithConversion {

  /**
   * Upload file with conversion.
   *
   * @return Inserted file id if successful, {@code null} otherwise.
   * @throws IOException if service account credentials file not found.
   */
  public static String uploadWithConversion() throws IOException {
    // Load pre-authorized user credentials from the environment.
    // TODO(developer) - See https://developers.google.com/identity for
    // guides on implementing OAuth2 for your application.
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
        .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
        credentials);

    // Build a new authorized API client service.
    Drive service = new Drive.Builder(new NetHttpTransport(),
        GsonFactory.getDefaultInstance(),
        requestInitializer)
        .setApplicationName("Drive samples")
        .build();

    // File's metadata.
    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);
    try {
      File file = service.files().create(fileMetadata, mediaContent)
          .setFields("id")
          .execute();
      System.out.println("File ID: " + file.getId());
      return file.getId();
    } catch (GoogleJsonResponseException e) {
      // TODO(developer) - handle error appropriately
      System.err.println("Unable to move file: " + e.getDetails());
      throw e;
    }
  }
}

Python

drive/snippets/drive-v3/file_snippet/upload_with_conversion.py
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


def upload_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 client
    service = 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-member
    file = (
        service.files()
        .create(body=file_metadata, media_body=media, fields="id")
        .execute()
    )
    print(f'File with ID: "{file.get("id")}" has been uploaded.')

  except HttpError as error:
    print(f"An error occurred: {error}")
    file = None

  return file.get("id")


if __name__ == "__main__":
  upload_with_conversion()

Node.js

drive/snippets/drive_v3/file_snippets/upload_with_conversion.js
/**
 * Upload file with conversion
 * @return{obj} file Id
 * */
async function uploadWithConversion() {
  const fs = require('fs');
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');
  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});
  const fileMetadata = {
    name: 'My Report',
    mimeType: 'application/vnd.google-apps.spreadsheet',
  };
  const media = {
    mimeType: 'text/csv',
    body: fs.createReadStream('files/report.csv'),
  };

  try {
    const file = await service.files.create({
      resource: fileMetadata,
      media: media,
      fields: 'id',
    });
    console.log('File Id:', file.data.id);
    return file.data.id;
  } catch (err) {
    // TODO(developer) - Handle error
    throw err;
  }
}

PHP

drive/snippets/drive_v3/src/DriveUploadWithConversion.php
use 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
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;

namespace DriveV3Snippets
{
    // Class to demonstrate Drive's upload with conversion use-case.
    public class UploadWithConversion
    {
        /// <summary>
        /// Upload file with conversion.
        /// </summary>
        /// <param name="filePath">Id of the spreadsheet file.</param>
        /// <returns>Inserted file id if successful, null otherwise.</returns>
        public static string DriveUploadWithConversion(string filePath)
        {
            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. */
                GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                    .CreateScoped(DriveService.Scope.Drive);

                // Create Drive API service.
                var service = new DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Drive API Snippets"
                });

                // Upload file My Report on drive.
                var fileMetadata = new Google.Apis.Drive.v3.Data.File()
                {
                    Name = "My Report",
                    MimeType = "application/vnd.google-apps.spreadsheet"
                };
                FilesResource.CreateMediaUpload request;
                // Create a new drive.
                using (var stream = new FileStream(filePath,
                           FileMode.Open))
                {
                    // Create a new file, with metadata and stream.
                    request = service.Files.Create(
                        fileMetadata, stream, "text/csv");
                    request.Fields = "id";
                    request.Upload();
                }

                var file = request.ResponseBody;
                // Prints the uploaded file id.
                Console.WriteLine("File ID: " + file.Id);
                return file.Id;
            }
            catch (Exception e)
            {
                // TODO(developer) - handle error appropriately
                if (e is AggregateException)
                {
                    Console.WriteLine("Credential Not found");
                }
                else if (e is FileNotFoundException)
                {
                    Console.WriteLine("File not found");
                }
                else
                {
                    throw;
                }
            }
            return null;
        }
    }
}

如需了解是否有可用的转换,请先检查 about 资源的 importFormats 数组,然后再创建该文件。此数组中动态提供支持的转化数据。一些常见的导入格式如下:

发件人
Microsoft Word、OpenDocument 文本、HTML、RTF、纯文本Google 文档
Microsoft Excel、OpenDocument 电子表格、CSV、TSV、纯文本Google 表格
Microsoft PowerPoint、OpenDocument 演示文稿Google 幻灯片
JPEG、PNG、GIF、BMP、PDFGoogle 文档(将图片嵌入到文档中)
纯文本(特殊 MIME 类型)、JSONGoogle Apps 脚本

在向文档、表格或幻灯片文件发出 update 请求期间上传并转换媒体内容时,文档的全部内容将被替换。

当您将图片转换为文档时,云端硬盘会使用光学字符识别 (OCR) 功能将图片转换为文本。您可以通过在 ocrLanguage 参数中指定适用的 BCP 47 语言代码来提高 OCR 算法的质量。提取的文本会与嵌入的图片一起显示在文档中。

使用预先生成的 ID 上传文件

借助 Drive API,您可以检索用于上传和创建资源的预生成文件 ID 列表。上传请求和文件创建请求可以使用这些预先生成的 ID。设置文件元数据中的 id 字段。

如需创建预先生成的 ID,请使用要创建的 ID 数量调用 files.generateIds

如果出现不确定的服务器错误或超时情况,您可以放心地使用预先生成的 ID 重新尝试上传。如果文件已成功创建,则后续重试会返回 HTTP 409 错误,并且不会创建重复的文件。

为未知文件类型定义可编入索引的文本

用户可以使用云端硬盘界面查找文档内容。您还可以使用 files.listfullText 字段搜索应用中的内容。如需了解详情,请参阅搜索文件和文件夹

云端硬盘在识别文件类型(包括文本文档、PDF、带文本的图片和其他常见类型)后,会自动将文档编入索引以供搜索。如果您的应用保存其他类型的文件(例如绘图、视频和快捷方式),您可以在文件的 contentHints.indexableText 字段中提供可编入索引的文本,以提高可检测性。

如需详细了解可编入索引的文本,请参阅管理文件元数据