上传文件数据

通过 Google Drive API,您可以在创建或更新 File。有关如何创建 仅包含元数据的文件(例如文件夹),请参阅创建仅包含元数据的文件

您可以执行的上传操作有三种:

  • 简单上传 (uploadType=media):使用此上传类型来传输 小型媒体文件(5 MB 或更小),而无需提供元数据。要执行 简单上传,请参阅执行简单上传

  • 多部分上传 (uploadType=multipart):“使用此上传类型 传输一个小文件(5 MB 或更小)以及描述 文件。要执行多部分上传,请参阅执行 多部分上传

  • 可续传上传 (uploadType=resumable):此上传类型适用于 大型文件(大于 5 MB)且网络连接的 例如在通过移动应用创建文件时可续传 对大多数应用来说,上传也是一种不错的选择 ,最低费用,即每次上传时都要多发出一个 HTTP 请求。 要执行可续传上传,请参阅执行可续传 上传

Google API 客户端库至少实现了以下其中一种类型的 上传。参阅客户端库 文档。 使用每种类型

使用“PATCH”而非“PUT

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

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

  • 使用 API 参考中记录的 HTTP 动词来处理 可续传上传,或用于简单上传或多部分上传的唯一请求。
  • PUT 用于可续传上传的所有后续请求, 请求已开始生效。无论 方法。

执行简单上传

要执行简单上传,请使用 files.create 方法, uploadType=media

下面展示了如何执行简单上传:

HTTP

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

    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. 使用查询创建对方法的 /upload URI 的 POST 请求 uploadType=multipart 的参数:

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

  2. 创建请求正文。根据 multipart/related content type RFC 2387, 包括两个部分:

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

    使用定界字符串标识每个部分,后跟两个连字符。在 在最后一个边界字符串后面添加两个连字符。

  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 字段中指定的扩展名。

执行可续传上传

通过可续传上传,您可以在完成通信后恢复上传操作。 会中断数据流因为您不必在 Compute Engine 中 从一开始就从零开始上传文件,可续传上传也可以降低您的带宽 网络故障时的数据使用

当您的文件大小可能有很大差异,或者 请求(如移动操作系统后台任务和 某些 App Engine 请求)。您还可以使用可续传上传 需要显示上传进度条的情况。

可续传上传包含几个概要步骤:

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

发送初始请求

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

HTTP

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

    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 状态代码。此外,响应在 包含用于指定可续传会话 URI 的 Location 标头。 使用可续传会话 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 标头来指示 文件未知。例如,如果您的Content-Range*/2000000 文件总长度为 2,000,000 字节。如果您不知道 请将 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 文档,以便充分利用其 功能。

如需将文件转换为特定的 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({
      requestBody: 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) 可将图片转换为文本。您可以 通过指定适用的 BCP,提高 OCR 算法的质量 47 语言代码 在 ocrLanguage 参数。提取的文本会与嵌入的图片一起显示在文档中。

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

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

要创建预先生成的 ID,请调用 files.generateIds(带有 要创建的 ID 的数量。

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

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

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

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

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