고급 드라이브 서비스

고급 드라이브 서비스를 사용하면 Apps Script에서 Google Drive API를 사용할 수 있습니다. Apps Script의 기본 제공 드라이브 서비스와 마찬가지로 이 API를 사용하면 스크립트로 Google Drive에서 파일과 폴더를 생성, 검색, 수정할 수 있습니다. 대부분의 경우 기본 제공 서비스를 사용하기가 더 쉽지만, 이 고급 서비스는 맞춤 파일 속성에 대한 액세스와 파일 및 폴더의 버전을 포함한 몇 가지 추가 기능을 제공합니다.

참조

이 서비스에 관한 자세한 내용은 Google Drive API의 참조 문서를 확인하세요. Apps Script의 모든 고급 서비스와 마찬가지로 고급 Drive 서비스는 공개 API와 동일한 객체, 메서드, 매개변수를 사용합니다. 자세한 내용은 메서드 서명 확인 방법을 참조하세요.

문제를 신고하고 다른 지원을 받으려면 Drive API 지원 가이드를 참고하세요.

샘플 코드

이 섹션의 코드 샘플은 API 버전 3을 사용합니다.

파일 업로드

다음 코드 샘플은 사용자의 Drive에 파일을 저장하는 방법을 보여줍니다.

advanced/drive.gs
/**
 * Uploads a new file to the user's Drive.
 */
function uploadFile() {
  try {
    // Makes a request to fetch a URL.
    const image = UrlFetchApp.fetch('http://goo.gl/nd7zjB').getBlob();
    let file = {
      name: 'google_logo.png',
      mimeType: 'image/png'
    };
    // Create a file in the user's Drive.
    file = Drive.Files.create(file, image, {'fields': 'id,size'});
    console.log('ID: %s, File size (bytes): %s', file.id, file.size);
  } catch (err) {
    // TODO (developer) - Handle exception
    console.log('Failed to upload file with error %s', err.message);
  }
}

폴더 나열

다음 코드 샘플은 사용자 드라이브에 있는 최상위 폴더를 나열하는 방법을 보여줍니다. 전체 결과 목록에 액세스하려면 페이지 토큰을 사용하세요.

advanced/drive.gs
/**
 * Lists the top-level folders in the user's Drive.
 */
function listRootFolders() {
  const query = '"root" in parents and trashed = false and ' +
    'mimeType = "application/vnd.google-apps.folder"';
  let folders;
  let pageToken = null;
  do {
    try {
      folders = Drive.Files.list({
        q: query,
        pageSize: 100,
        pageToken: pageToken
      });
      if (!folders.files || folders.files.length === 0) {
        console.log('All folders found.');
        return;
      }
      for (let i = 0; i < folders.files.length; i++) {
        const folder = folders.files[i];
        console.log('%s (ID: %s)', folder.name, folder.id);
      }
      pageToken = folders.nextPageToken;
    } catch (err) {
      // TODO (developer) - Handle exception
      console.log('Failed with error %s', err.message);
    }
  } while (pageToken);
}

버전 나열

다음 코드 샘플은 지정된 파일의 버전을 나열하는 방법을 보여줍니다. 일부 파일에는 여러 버전이 있을 수 있으며 전체 결과 목록에 액세스하려면 페이지 토큰을 사용해야 합니다.

advanced/drive.gs
/**
 * Lists the revisions of a given file.
 * @param {string} fileId The ID of the file to list revisions for.
 */
function listRevisions(fileId) {
  let revisions;
  const pageToken = null;
  do {
    try {
      revisions = Drive.Revisions.list(
          fileId,
          {'fields': 'revisions(modifiedTime,size),nextPageToken'});
      if (!revisions.revisions || revisions.revisions.length === 0) {
        console.log('All revisions found.');
        return;
      }
      for (let i = 0; i < revisions.revisions.length; i++) {
        const revision = revisions.revisions[i];
        const date = new Date(revision.modifiedTime);
        console.log('Date: %s, File size (bytes): %s', date.toLocaleString(),
            revision.size);
      }
      pageToken = revisions.nextPageToken;
    } catch (err) {
      // TODO (developer) - Handle exception
      console.log('Failed with error %s', err.message);
    }
  } while (pageToken);
}

파일 속성 추가

다음 코드 샘플에서는 appProperties 필드를 사용하여 파일에 커스텀 속성을 추가합니다. 커스텀 속성은 스크립트에만 표시됩니다. 다른 앱에도 표시되는 파일에 맞춤 속성을 추가하려면 properties 필드를 대신 사용하세요. 자세한 내용은 커스텀 파일 속성 추가를 참고하세요.

advanced/drive.gs
/**
 * Adds a custom app property to a file. Unlike Apps Script's DocumentProperties,
 * Drive's custom file properties can be accessed outside of Apps Script and
 * by other applications; however, appProperties are only visible to the script.
 * @param {string} fileId The ID of the file to add the app property to.
 */
function addAppProperty(fileId) {
  try {
    let file = {
      'appProperties': {
        'department': 'Sales'
      }
    };
    // Updates a file to add an app property.
    file = Drive.Files.update(file, fileId, null, {'fields': 'id,appProperties'});
    console.log(
        'ID: %s, appProperties: %s',
        file.id,
        JSON.stringify(file.appProperties, null, 2));
  } catch (err) {
    // TODO (developer) - Handle exception
    console.log('Failed with error %s', err.message);
  }
}