上传文件数据

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

您可以上传以下 3 种类型的数据:

  • 简单上传 (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. 使用 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
from __future__ import print_function

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] 设置正文的格式,其中包含 2 个部分:

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

    使用边界字符串(后跟 2 个连字符)标识每个部分。此外,请在最后一个边界字符串后添加 2 个连字符。

  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 状态代码。此外,响应中包含一个用于指定可续传会话 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 表示您要上传某个 2,000,000 字节文件中的前 524,288 个字节 (256 x 1024 x 2)。
  4. 发送请求并处理响应。如果上传请求被中断,或者您收到 5xx 响应,请按照恢复中断的上传部分中的步骤操作。

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

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

恢复中断的上传

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

HTTP

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

  2. 添加 Content-Range 标头,以表明文件中的当前位置未知。例如,如果您的文件总长度为 2,000,000 字节,请将 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 错误,请参阅解决 5xx 错误
  • 如果遇到 403 rate limit 个错误,请重新尝试上传。如需详细了解如何处理 403 rate limit 错误,请参阅解决 403 error: Rate limit exceeded 问题
  • 如果在可续传上传期间出现任何 4xx 错误(包括 403),请重新开始上传。这些错误表示上传会话已过期,您必须通过请求新的会话 URI 来重启。上传会话也会在处于非活跃状态一周后过期。

导入到 Google 文档类型

在云端硬盘中创建文件时,您可能需要将文件转换为 Google Workspace 文件类型,例如 Google 文档或 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
from __future__ import print_function

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

如需了解转换是否可用,请在创建文件之前查看关于资源的 importFormats 数组。受支持的转化可通过此数组动态提供。一些常见的导入格式包括:

发件人发送至
Microsoft Word、OpenDocument Text、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,请调用 file.generateIds,其中包含要创建的 ID 数量。

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

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

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

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

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