파일 데이터 업로드

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를 사용합니다. 요청이 시작됩니다. 이러한 요청은 메서드를 호출할 수 있습니다.

간단한 업로드 실행

간단한 업로드를 수행하려면 files.create 메서드를 다음과 같이 바꿉니다. uploadType=media입니다.

다음은 간단한 업로드를 수행하는 방법을 보여줍니다.

HTTP

  1. 쿼리를 사용하여 메서드의 /upload 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입니다.

다음은 멀티파트 업로드를 수행하는 방법을 보여줍니다.

자바

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. 쿼리를 사용하여 메서드의 /upload 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(으)로 설정되었습니다. 파일의 메타데이터 추가 볼 수 있습니다
    • 미디어. 미디어는 두 번째 위치에 있어야 하며 Content-Type 헤더가 있어야 합니다. 모든 MIME 유형 중에서 선택할 수 있습니다. 파일의 데이터를 미디어 부분에 추가합니다.

    앞에 하이픈 2개를 추가한 경계 문자열로 각 부분을 식별합니다. 포함 또한 최종 경계 문자열 뒤에 하이픈 2개를 추가합니다.

  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를 호출하면 읽기 전용 fileExtension 속성이 반환됩니다. name 필드에 원래 지정된 확장자를 포함합니다.

재개 가능한 업로드 수행

재개 가능한 업로드를 사용하면 커뮤니케이션이 끝난 후 업로드 작업을 재개할 수 있습니다. 데이터의 흐름을 방해할 수 있습니다 대규모 컴퓨터를 다시 시작할 필요가 없기 때문에 재개 가능한 업로드를 사용하면 대역폭이 줄어들 수 있습니다. 네트워크 장애가 있는 경우 사용량에 제한이 있습니다

재개 가능한 업로드는 파일 크기가 크게 달라지거나 요청에 대한 시간 제한이 고정되어 있습니다 (예: 모바일 OS 백그라운드 작업 및 특정 App Engine 요청)에 사용할 수 있습니다. 또한 업로드 진행률 표시줄을 표시하고 싶을 수 있습니다

재개 가능한 업로드는 다음과 같은 몇 가지 상위 단계로 구성됩니다.

  1. 초기 요청을 전송하고 재개 가능한 세션 URI를 검색합니다.
  2. 데이터를 업로드하고 업로드 상태를 모니터링합니다.
  3. (선택사항) 업로드에 문제가 있으면 업로드를 재개합니다.

초기 요청 전송

재개 가능한 업로드를 시작하려면 files.create 메서드를 다음과 같이 바꿉니다. uploadType=resumable입니다.

HTTP

  1. 쿼리를 사용하여 메서드의 /upload 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. 파일의 메타데이터가 있는 경우 요청 본문에 메타데이터를 추가합니다. 볼 수 있습니다 그렇지 않으면 요청 본문을 비워 둡니다.

  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. 콘텐츠 업로드로 이동합니다.

콘텐츠 업로드

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

  • 단일 요청으로 콘텐츠 업로드: 파일을 여러 개 업로드할 수 있을 때 하나의 요청으로 업로드할 수 있으며, 업로드 진행률 표시기를 표시할 필요가 없습니다. 이 요구 사항이 적고 결과적으로 확인할 수 있습니다
  • 여러 단위로 콘텐츠 업로드: 이 방법은 단일 요청으로 전송되는 데이터의 양을 줄일 수 있습니다 필요한 경우 개별 사용자에 대한 고정된 시간 제한이 있을 때 전송되는 데이터를 줄이기 위해 요청을 처리할 수 있습니다. 또한 이 접근 방식은 업로드 진행 상황이 표시됩니다.

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는 처음 524,288바이트 (256 x 1,024 x 2)를 2,000,000바이트 파일로 전송합니다.
  4. 요청을 전송하고 응답을 처리합니다. 업로드 요청이 5xx 응답을 받으면 중단된 업로드를 재개합니다.

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

전체 파일 업로드가 완료되면 200 OK 또는 201 Created 응답 및 리소스와 연결된 모든 메타데이터입니다.

중단된 업로드 재개

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

HTTP

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

  2. Content-Range 헤더를 추가하여 알 수 없는 파일입니다. 예를 들어 다음과 같은 경우 Content-Range*/2000000로 설정합니다. 총 파일 길이는 2,000,000바이트입니다. 파일의 전체 크기를 모르는 경우 파일에서 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를 요청하여 다시 시작하는 경우 세션 업로드 1주일 동안 사용하지 않으면 만료됩니다.

Google Docs 유형으로 가져오기

Drive에서 파일을 만들 때 파일을 Google Workspace 파일 형식(예: Google Docs 또는 Sheets를 탭합니다. 예를 들어 0과 0의 다른 위치에서 문서를 즐겨 사용하는 워드 프로세서를 Docs에 통합하여 기능을 살펴보겠습니다

파일을 특정 Google Workspace 파일 형식으로 변환하려면 파일을 만들 때 Google Workspace mimeType

다음은 CSV 파일을 Google Workspace 시트로 변환하는 방법을 보여줍니다.

자바

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

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 배열을 확인하세요. 지원되는 전환은 이 배열에 동적으로 제공됩니다. 자주 사용되는 가져오기 형식은 다음과 같습니다.

From받는사람
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 파일에서 문서의 전체 내용이 대체됩니다.

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

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

Drive API를 사용하면 리소스를 업로드하고 만드는 데 사용됩니다 업로드 및 파일 생성 요청은 사전 생성된 ID를 사용하세요 파일 메타데이터에서 id 필드를 설정합니다.

미리 생성된 ID를 만들려면 다음을 호출합니다. files.generateIds: 만들 ID의 수입니다.

확인되지 않은 ID가 있으면 미리 생성된 ID로 업로드를 안전하게 다시 시도할 수 있습니다. 서버 오류 또는 시간 초과가 발생했습니다. 파일이 성공적으로 생성되면 재시도하면 HTTP 409 오류가 반환되며 중복 파일이 생성되지 않습니다.

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

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

Drive가 문서를 검색할 때 자동으로 색인을 생성합니다. 텍스트 문서, PDF, 텍스트가 있는 이미지 및 기타 일반적인 유형 앱이 다른 유형의 파일 (예: 그림, 동영상, 바로 가기)에서 제공하는 도구를 사용하여 검색 가능성을 높일 수 있습니다. 파일의 contentHints.indexableText 필드에 있는 색인 생성 가능 텍스트입니다.

색인 생성이 가능한 텍스트에 관한 자세한 내용은 파일 관리 메타데이터를 참고하세요.