파일 데이터 업로드

Google Drive API를 사용하면 File를 만들거나 업데이트할 때 파일 데이터를 업로드할 수 있습니다. 폴더와 같은 메타데이터 전용 파일을 만드는 방법에 대한 자세한 내용은 메타데이터 전용 파일 만들기를 참조하세요.

다음과 같은 세 가지 유형의 업로드를 수행할 수 있습니다.

  • 단순 업로드 (uploadType=media): 메타데이터를 제공하지 않고 작은 미디어 파일 (5MB 이하)을 전송하려면 이 업로드 유형을 사용합니다. 간단한 업로드를 수행하려면 간단한 업로드 실행을 참조하세요.

  • 멀티파트 업로드 (uploadType=multipart): '이 업로드 유형을 사용하여 파일을 설명하는 메타데이터와 함께 작은 파일 (5MB 이하)을 단일 요청으로 전송합니다. 멀티파트 업로드를 수행하려면 멀티파트 업로드 실행을 참고하세요.

  • 재개 가능한 업로드 (uploadType=resumable): 대용량 파일 (5MB 초과)과 모바일 앱에서 파일을 만들 때와 같이 네트워크 중단 가능성이 높은 경우에 이 업로드 유형을 사용합니다. 재개 가능한 업로드는 업로드당 추가 HTTP 요청 1개의 최소 비용으로 작은 파일에서도 작동하므로 대부분의 애플리케이션에 적합합니다. 재개 가능한 업로드를 실행하려면 재개 가능한 업로드 실행을 참고하세요.

Google API 클라이언트 라이브러리는 이러한 유형의 업로드를 하나 이상 구현합니다. 각 유형을 사용하는 방법에 관한 자세한 내용은 클라이언트 라이브러리 문서를 참고하세요.

PATCH vs. PUT 사용

HTTP 동사 PATCH는 부분 파일 리소스 업데이트를 지원하는 반면, HTTP 동사 PUT는 전체 리소스 대체를 지원합니다. 기존 리소스에 새 필드를 추가할 때 PUT로 인해 브레이킹 체인지가 발생할 수 있습니다.

파일 리소스를 업로드할 때 다음 가이드라인을 따르세요.

  • 재개 가능한 업로드의 초기 요청이나 단순 또는 멀티파트 업로드의 유일한 요청에는 API 참조에 설명된 HTTP 동사를 사용하세요.
  • 요청이 시작되면 재개 가능한 업로드에 대한 모든 후속 요청에 PUT를 사용합니다. 이러한 요청은 호출되는 메서드에 관계없이 콘텐츠를 업로드합니다.

간단한 업로드 수행

간단한 업로드를 실행하려면 uploadType=media와 함께 files.create 메서드를 사용합니다.

다음은 간단한 업로드 방법을 보여줍니다.

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

2,399필리핀

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. 요청을 전송합니다.

연결된 데이터 없이 메타데이터 부분만 만들거나 업데이트하려면 POST 또는 PATCH 요청을 표준 리소스 엔드포인트(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. (선택사항) 업로드에 방해가 되면 업로드를 재개합니다.

초기 요청 전송

재개 가능한 업로드를 시작하려면 uploadType=resumable와 함께 files.create 메서드를 사용합니다.

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. 재개 가능한 세션 URL을 복사하여 저장합니다.

  6. 계속해서 콘텐츠 업로드를 진행합니다.

콘텐츠 업로드

재개 가능한 세션으로 파일을 업로드하는 방법에는 두 가지가 있습니다.

  • 단일 요청으로 콘텐츠 업로드: 한 번의 요청으로 파일을 업로드할 수 있는 경우, 단일 요청에 정해진 시간 제한이 없거나 업로드 진행률 표시기를 표시할 필요가 없는 경우 이 방법을 사용합니다. 이 접근 방식은 요청 횟수가 더 적고 성능이 향상되므로 가장 좋습니다.
  • 콘텐츠를 여러 단위로 업로드: 단일 요청으로 전송되는 데이터의 양을 줄여야 하는 경우 이 방법을 사용합니다. App Engine 요청의 특정 클래스처럼 개별 요청에 정해진 시간제한이 있는 경우 전송되는 데이터를 줄여야 할 수도 있습니다. 이 접근 방식은 업로드 진행률을 표시하는 맞춤 표시기를 제공해야 하는 경우에도 유용합니다.

HTTP - 단일 요청

  1. 재개 가능한 세션 URI에 대한 PUT 요청을 작성합니다.
  2. 파일의 데이터를 요청 본문에 추가합니다.
  3. Content-Length HTTP 헤더를 추가하고 파일의 바이트 수로 설정합니다.
  4. 요청을 전송합니다. 업로드 요청이 중단되거나 5xx 응답을 받으면 중단된 업로드 재개 절차를 따릅니다.

HTTP - 여러 요청

  1. 재개 가능한 세션 URI에 대한 PUT 요청을 작성합니다.

  2. 단위의 데이터를 요청 본문에 추가합니다. 업로드를 완료하는 마지막 단위를 제외하고 256KB (256 x 1, 024바이트)의 배수로 단위를 만듭니다. 효율적인 업로드가 가능하도록 단위 크기를 최대한 크게 유지합니다.

  3. 다음 HTTP 헤더를 추가합니다.

    • Content-Length. 현재 단위의 바이트 수로 설정합니다.
    • Content-Range. 파일에서 업로드하는 바이트를 표시하도록 설정합니다. 예를 들어 Content-Range: bytes 0-524287/2000000는 2, 000,000바이트 크기의 파일 중 첫 524,288바이트 (256 x 1,024 x 2)를 업로드한다는 의미입니다.
  4. 요청을 전송하고 응답을 처리합니다. 업로드 요청이 중단되거나 5xx 응답을 받으면 중단된 업로드 재개 절차를 따릅니다.

  5. 파일에 남아 있는 각 단위에 대해 1~4단계를 반복합니다. 응답의 Range 헤더를 사용하여 다음 단위의 시작 위치를 결정합니다. 서버가 이전 요청에서 전송된 모든 바이트를 수신했다고 가정하지 마세요.

전체 파일 업로드가 완료되면 리소스와 관련된 메타데이터와 함께 200 OK 또는 201 Created 응답을 받습니다.

중단된 업로드 재개

응답 전에 업로드 요청이 종료되거나 503 Service Unavailable 응답을 받은 경우에는 중단된 업로드를 재개해야 합니다.

HTTP

  1. 업로드 상태를 요청하려면 재개 가능한 세션 URI에 대한 비어 있는 PUT 요청을 작성합니다.

  2. Content-Range 헤더를 추가하여 파일의 현재 위치를 알 수 없음을 나타냅니다. 예를 들어 총 파일 길이가 2,000,000바이트이면 Content-Range*/2000000로 설정합니다. 파일 전체 크기를 모르면 Content-Range*/*로 설정합니다.

  3. 요청을 전송합니다.

  4. 다음과 같이 응답을 처리합니다.

    • 200 OK 또는 201 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 Docs 유형으로 가져오기

Drive에서 파일을 만들 때 파일을 Google Docs 또는 Sheets와 같은 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({
      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;
  }
}

2,399필리핀

drive/snippets/drive_v3/src/DriveUploadWithConversion.php
use Google\Client;
use Google\Service\Drive;
function uploadWithConversion()
{
    try {
        $client = new Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope(Drive::DRIVE);
        $driveService = new Drive($client);
        $fileMetadata = new Drive\DriveFile(array(
            'name' => 'My Report',
            'mimeType' => 'application/vnd.google-apps.spreadsheet'));
        $content = file_get_contents('../files/report.csv');
        $file = $driveService->files->create($fileMetadata, array(
            'data' => $content,
            'mimeType' => 'text/csv',
            'uploadType' => 'multipart',
            'fields' => 'id'));
        printf("File ID: %s\n", $file->id);
        return $file->id;
    } catch(Exception $e) {
        echo "Error Message: ".$e;
    }

}

.NET

drive/snippets/drive_v3/DriveV3Snippets/UploadWithConversion.cs
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;

namespace DriveV3Snippets
{
    // Class to demonstrate Drive's upload with conversion use-case.
    public class UploadWithConversion
    {
        /// <summary>
        /// Upload file with conversion.
        /// </summary>
        /// <param name="filePath">Id of the spreadsheet file.</param>
        /// <returns>Inserted file id if successful, null otherwise.</returns>
        public static string DriveUploadWithConversion(string filePath)
        {
            try
            {
                /* Load pre-authorized user credentials from the environment.
                 TODO(developer) - See https://developers.google.com/identity for
                 guides on implementing OAuth2 for your application. */
                GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                    .CreateScoped(DriveService.Scope.Drive);

                // Create Drive API service.
                var service = new DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Drive API Snippets"
                });

                // Upload file My Report on drive.
                var fileMetadata = new Google.Apis.Drive.v3.Data.File()
                {
                    Name = "My Report",
                    MimeType = "application/vnd.google-apps.spreadsheet"
                };
                FilesResource.CreateMediaUpload request;
                // Create a new drive.
                using (var stream = new FileStream(filePath,
                           FileMode.Open))
                {
                    // Create a new file, with metadata and stream.
                    request = service.Files.Create(
                        fileMetadata, stream, "text/csv");
                    request.Fields = "id";
                    request.Upload();
                }

                var file = request.ResponseBody;
                // Prints the uploaded file id.
                Console.WriteLine("File ID: " + file.Id);
                return file.Id;
            }
            catch (Exception e)
            {
                // TODO(developer) - handle error appropriately
                if (e is AggregateException)
                {
                    Console.WriteLine("Credential Not found");
                }
                else if (e is FileNotFoundException)
                {
                    Console.WriteLine("File not found");
                }
                else
                {
                    throw;
                }
            }
            return null;
        }
    }
}

변환을 사용할 수 있는지 확인하려면 파일을 만들기 전에 about 리소스의 importFormats 배열을 확인하세요. 지원되는 변환은 이 배열에서 동적으로 사용할 수 있습니다. 일반적인 가져오기 형식은 다음과 같습니다.

보낸 사람
Microsoft Word, OpenDocument 텍스트, HTML, RTF, 일반 텍스트Google Docs
Microsoft Excel, OpenDocument 스프레드시트, CSV, TSV, 일반 텍스트Google Sheets
Microsoft PowerPoint, OpenDocument 프레젠테이션Google Slides
JPEG, PNG, GIF, BMP, PDFGoogle Docs (이미지를 문서에 삽입)
일반 텍스트 (특수 MIME 유형), JSONGoogle Apps Script

update 요청 중에 Docs, Sheets 또는 Slides 파일에 미디어를 업로드하고 변환하면 문서의 전체 콘텐츠가 교체됩니다.

이미지를 문서로 변환하면 드라이브는 광학 문자 인식 (OCR)을 사용하여 이미지를 텍스트로 변환합니다. ocrLanguage 매개변수에 적용 가능한 BCP 47 언어 코드를 지정하여 OCR 알고리즘의 품질을 개선할 수 있습니다. 추출된 텍스트는 삽입된 이미지와 함께 문서에 표시됩니다.

사전 생성된 ID를 사용하여 파일 업로드

Drive API를 사용하면 리소스를 업로드하고 만드는 데 사용되는 사전 생성된 파일 ID 목록을 검색할 수 있습니다. 업로드 및 파일 생성 요청은 이러한 사전 생성된 ID를 사용할 수 있습니다. 파일 메타데이터에서 id 필드를 설정합니다.

사전 생성된 ID를 만들려면 만들 ID 수와 함께 files.generateIds를 호출합니다.

불확실한 서버 오류 또는 시간 초과가 발생하는 경우 사전 생성된 ID로 업로드를 안전하게 재시도할 수 있습니다. 파일이 성공적으로 생성된 경우 이후 재시도하면 HTTP 409 오류가 반환되고 중복 파일이 생성되지 않습니다.

알 수 없는 파일 형식에 대해 색인 생성이 가능한 텍스트 정의

사용자는 Drive UI를 사용하여 문서 콘텐츠를 찾을 수 있습니다. files.listfullText 필드를 사용하여 앱에서 콘텐츠를 검색할 수도 있습니다. 자세한 내용은 파일 및 폴더 검색을 참고하세요.

Drive가 텍스트 문서, PDF, 텍스트가 포함된 이미지, 기타 일반적인 유형 등 파일 형식을 인식하면 검색할 문서에 자동으로 색인을 생성합니다. 앱이 다른 유형의 파일 (예: 그림, 동영상, 바로가기)을 저장하는 경우 파일의 contentHints.indexableText 필드에 색인을 생성할 수 있는 텍스트를 제공하여 검색 가능성을 개선할 수 있습니다.

색인을 생성할 수 있는 텍스트에 대한 자세한 내용은 파일 메타데이터 관리를 참조하세요.