上傳檔案資料

Google Drive API 可讓您在建立或更新 File 時上傳檔案資料。如要瞭解如何建立僅包含中繼資料的檔案,例如資料夾,請參閱建立僅限中繼資料的檔案

您可以執行三種上傳類型:

  • 簡易上傳 (uploadType=media):使用此上傳類型來傳輸小型媒體檔案 (大小不超過 5 MB),但不提供中繼資料。如要執行簡易上傳,請參閱「執行簡易上傳」一文。

  • 多部分上傳作業 (uploadType=multipart):「使用此上傳類型可在單一要求中傳輸一個小型檔案 (5 MB 以下) 及說明檔案的中繼資料。如要執行多部分上傳作業,請參閱執行多部分上傳作業

  • 支援續傳的上傳作業 (uploadType=resumable):這種上傳類型適合大型檔案 (大小超過 5 MB),以及在非常可能網路中斷時 (例如從行動應用程式建立檔案) 使用。支援續傳的上傳功能對大多數應用程式來說也是不錯的選擇,因為這類上傳也適用於每次上傳的小型檔案。如要執行支援續傳的上傳作業,請參閱執行支援續傳的上傳作業

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 設定內文格式,其中包含兩個部分:

    • 中繼資料。中繼資料必須先提供,且必須將 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 狀態碼。此外,其中包含了指定續傳工作階段 URI 的 Location 標頭:

    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 錯誤,請參閱「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({
      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 陣列。這個陣列會以動態方式提供支援的轉換。部分常見的匯入格式如下:

From
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 要求期間上傳媒體並轉換為 Google 文件、試算表或簡報檔案時,系統會取代文件的完整內容。

當您將圖片轉換為文件時,雲端硬碟會使用光學字元辨識 (OCR) 將圖片轉換成文字。您可以在 ocrLanguage 參數中指定適用的 BCP 47 語言代碼,改善 OCR 演算法的品質。擷取的文字會和內嵌圖片一併顯示在 Google 文件中。

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

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

如要建立預先產生的 ID,請使用要建立的 ID 數量呼叫 files.generateIds

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

為不明檔案類型定義可建立索引的文字

使用者可以透過雲端硬碟使用者介面尋找文件內容。您也可以使用 files.listfullText 欄位搜尋應用程式的內容。詳情請參閱「搜尋檔案和資料夾」。

雲端硬碟在識別檔案類型 (包括文字文件、PDF、含有文字的圖片及其他常見類型) 時,會自動為文件建立索引以供搜尋。如果應用程式會儲存其他類型的檔案 (例如繪圖、影片和捷徑),您可以在檔案的 contentHints.indexableText 欄位中提供可建立索引的文字,藉此提高曝光度。

如要進一步瞭解可建立索引的文字,請參閱「管理檔案中繼資料」。