上傳檔案資料

您可以透過 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. 使用查詢對方法的 /上傳 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. 使用查詢對方法的 /上傳 URI 建立 POST 要求 uploadType=multipart 的參數:

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

  2. 建立要求主體。根據 多部分/相關內容類型 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 欄位中指定的副檔名。

執行支援續傳的上傳作業

支援續傳的上傳作業可讓您在通訊後繼續執行上傳作業 資料流動中斷使用 BigQuery 時 從開始上傳且支援續傳的上傳作業,也能降低您的頻寬用量 以及網路故障的情形。

當您的檔案大小可能大幅差異,或發生在什麼情況下,支援續傳的上傳作業就能派上用場 行動作業系統背景工作等要求有固定的時間限制 特定 App Engine 要求)。您也能將支援續傳的上傳作業用於 選擇顯示上傳進度列的情況

支援續傳的上傳作業包含數個高階步驟:

  1. 傳送初始要求,並擷取可續傳的工作階段 URI。
  2. 上傳資料並監控上傳狀態。
  3. (選用) 如果上傳作業受到干擾,請繼續進行上傳作業。

傳送初始要求

如要開始進行支援續傳的上傳作業,請使用 files.create 方法搭配 uploadType=resumable

HTTP

  1. 使用查詢對方法的 /上傳 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. 建立 PUT 要求以支援續傳工作階段 URI。
  2. 將檔案資料新增至要求主體。
  3. 新增 Content-Length HTTP 標頭,設為檔案中的位元組數。
  4. 傳送要求。如果上傳要求中斷,或您收到 5xx 回應,請按照「繼續執行中斷的上傳作業」一節的程序操作。

HTTP - 多個要求

  1. 建立 PUT 要求以支援續傳工作階段 URI。

  2. 將區塊的資料新增至要求主體。以倍數的方式建立區塊 大小為 256 KB (256 x 1024 位元組),但完成的最終區塊除外 即可。區塊越大越好 效率。

  3. 請新增下列 HTTP 標頭:

    • Content-Length。設為目前區塊中的位元組數。
    • Content-Range。設定為顯示上傳檔案中的位元組。適用對象 舉例來說,Content-Range: bytes 0-524287/2000000 會顯示您上傳 前 524,288 個位元組 (256 x 1024 x 2),位於 2,000,000 位元組檔案中。
  4. 傳送要求並處理回應。如果上傳要求 中斷或收到 5xx 回應時,請按照 繼續執行中斷的上傳作業

  5. 針對剩餘的檔案區塊,重複步驟 1 到 4。使用 回應中的 Range 標頭,以決定下一個區塊的起始位置。 請勿假設伺服器已收到先前要求中傳送的所有位元組。

整個檔案上傳完畢後,您會收到 200 OK,或 201 Created 回應,以及與資源相關聯的所有中繼資料。

繼續執行中斷的上傳作業

如果上傳要求在回應之前終止,或是您收到 503 Service Unavailable 回應,則您必須繼續執行中斷的上傳作業。

HTTP

  1. 如要索取上傳狀態,請建立空白的 PUT 要求至 支援續傳的工作階段 URI。

  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 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 Text、HTML、RTF、純文字Google 文件
Microsoft Excel、OpenDocument 試算表、CSV、TSV、純文字Google 試算表
Microsoft PowerPoint、OpenDocument 簡報Google 簡報
JPEG、PNG、GIF、BMP、PDFGoogle 文件 (將圖片嵌入文件中)
純文字 (特殊 MIME 類型)、JSONGoogle Apps Script

update 要求期間上傳媒體並轉換為 文件、試算表或簡報檔案 文件的所有內容都會被取代。

當你將圖片轉換為文件時,雲端硬碟會使用 光學字元辨識 (OCR) 功能可將圖片轉換為文字。你可以 指定適用的 BCP 來提升 OCR 演算法的品質 47 語言代碼 的 ocrLanguage敬上 參數。擷取的文字會顯示在文件中,嵌入圖片旁。

使用預先產生的 ID 上傳檔案

Drive API 可讓您擷取預先產生的檔案 ID 清單, 可用來上傳及建立資源上傳和檔案建立要求可以 請使用預先產生的 ID設定檔案中繼資料中的 id 欄位。

如要建立預先產生的 ID,請呼叫 files.generateIds,其中包含 數量。

如果不確定,可以使用預先產生的 ID 安全地重新上傳 伺服器錯誤或逾時。如果檔案已成功建立 重試傳回 HTTP 409 錯誤,且不會建立重複的檔案。

為未知的檔案類型定義可建立索引的文字

使用者可透過雲端硬碟 UI 尋找文件內容。你也可以 使用 files.listfullText 欄位來搜尋應用程式的內容。如需詳細資訊,請參閱「搜尋 檔案和資料夾

雲端硬碟會自動為文件建立索引,以便搜尋 辨識檔案類型,包括文字文件、PDF、含有文字的圖片 和其他常見類型如果您的應用程式儲存了其他類型的檔案 (例如繪圖、 及快速指令) 都可透過提供 檔案 contentHints.indexableText 欄位中的可建立索引文字。

如需更多關於可建立索引文字的資訊,請參閱管理檔案 中繼資料