Files in Google Drive

Advanced Drive Service in Apps Script에 이어서 Files and folders overview를 보면 파일 속성 중에 ID가 있습니다.

File attributes


File ID

A unique opaque ID for each file. File IDs are stable throughout the life of the file, even if the file name changes.

Files in Drive cannot be directly addressed by their path. Search expressions are used to locate files by name, type, content, parent container, owner, or other metadata.


제가 만든 복사 앱은 파일이나 폴더 URL을 입력 받아서 복사본을 만듭니다.


파일을 복사하기 위해서 drive.files.copy를 사용합니다.
이때 Parameter에 file Id를 넣어줘야 합니다.

Files: copy를 참고하세요.

따라서 파일이나 폴더 URL에서 파일 ID를 추출해야합니다.

예전에 stackoverflow에서 검색해서 코드에 적용했는데 조금 바뀌었네요.


Easiest way to get file ID from URL on Google Apps Script

https://stackoverflow.com/questions/16840038/easiest-way-to-get-file-id-from-url-on-google-apps-script/16840612


function getIdFromUrl(url) { 
return url.match(/[-\w]{25,}/); }


마지막에 있는 ID를 구하기 위해서 $를 추가했네요.

/[-\w]{25,}$/

$를 추가하면 파일 ID뒤에 따라오는(/edit) 것이 있을 때 안됩니다.

그리고 구글이 팀 드라이브( 공유 드라이브 )를 지원하면서 팀 드라이브 ID의 문자열 길이가 25보다 작을 수 있습니다.

제 앱은 팀 드라이브에 있는 파일을 복사할 수 있고 팀 드라이브에 복사본을 만들수도 있어서 문자열 길이를 25로 사용하면 안됩니다.


저는 이렇게 만들었습니다.

function getIdFromUrl(url) {
  try {
    return url.match(/[-\w]{15,}/g).pop();
  } catch(e) {
    console.warn('catch: %s, url: %s, get IdFromUrl', e, url);
  }
}


개발자 분들은 테스트해 보시고 사용하세요.




참고

Files you can store in Google Drive



Share files from Google Drive



Find files shared with you

Regular expression flags
g: 전역 검색



댓글

이 블로그의 인기 게시물

Duplicate files, Deduper in Google Drive