上傳檔案資料

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

你可以透過下列 3 種方式上傳:

  • 簡易上傳 (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。如果您的檔案較小,且檔案中繼資料不重要,您可以使用簡易上傳。

執行多部分上傳作業

多部分上傳要求可讓您在相同要求中上傳中繼資料和資料。如果您傳送的資料夠小,就算重新上傳一次,也想完整上傳,請使用這個選項。

如要執行多部分上傳作業,請搭配 uploadType=multipart 使用 files.create 方法。

以下說明如何執行多部分上傳作業:

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 的呼叫會傳回包含 name 欄位最初指定擴充功能的唯讀 fileExtension 屬性。

執行支援續傳的上傳作業

續傳上傳作業可讓您繼續通訊,使通訊作業中斷而中斷資料流。您不必從一開始就重新開始上傳大型檔案,因此如果網路故障,支援續傳的上傳作業也能降低頻寬用量。

如果檔案大小有顯著差異,或是要求有固定的時間限制 (例如行動 OS 背景工作和特定 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 狀態碼。此外,回應中包含的 Location 標頭會指定續傳工作階段 URI。 使用續傳工作階段 URI 上傳檔案資料,並查詢上傳狀態。支援工作階段的工作階段 URI 會在一週後失效。

  5. 複製並儲存續傳工作階段網址。

  6. 前往上傳內容

上傳內容

你可以透過下列 2 種方式上傳續傳工作階段的檔案:

  • 在單一要求中上傳內容:如果對任何要求沒有固定的時間限制,或者不需要顯示上傳進度指標,請使用這個方法。 這個方法最少,因為需要的要求數量較少,也有助於提升效能。
  • 將內容分成多個區塊:如果減少任何單一要求中傳輸的資料量,請使用這個方法。假如每個要求都有固定的時間限制,您可能需要減少傳輸的資料,就像某些 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 陣列。此陣列支援支援的轉換。常見的匯入格式包括:

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 要求並將該文件轉換為文件、試算表或簡報時,系統會取代文件的完整內容。

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

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

雲端硬碟 API 可讓您擷取系統自動產生的檔案 ID 清單,以便上傳及建立資源。上傳和檔案建立要求可以使用這些自動產生的 ID。設定檔案中繼資料的 id 欄位。

如要建立自動產生的 ID,請使用要建立的 ID 數量呼叫 file.generateIds

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

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

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

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

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