Cloud Storage에서 파일 및 폴더의 업로드, 업데이트 또는 삭제에 대한 응답으로 함수를 트리거할 수 있습니다.
이 페이지의 예는 이미지 파일이 Cloud Storage에 업로드될 때 트리거되는 샘플 함수를 기반으로 합니다. 이 샘플 함수는 이벤트 속성에 액세스하는 방법, Cloud Functions 인스턴스에 파일을 다운로드하는 방법, Cloud Storage 이벤트를 처리하는 기타 기본 사항을 보여줍니다.
사용 사례의 더 많은 예는 Cloud Functions로 무엇을 할 수 있나요? 를 참조하세요.
Cloud Storage 변경사항에 대한 함수 트리거
functions.storage
를 사용하여 Cloud Storage 이벤트를 처리하는 함수를 만듭니다. 함수 범위를 특정 Cloud Storage 버킷으로 지정할지 아니면 기본 버킷을 사용할지에 따라 다음 중 하나를 사용하세요.
-
functions.storage.object()
는 기본 Cloud Storage 버킷의 객체 변경사항을 수신 대기합니다. -
functions.storage.bucket('bucketName').object()
특정 버킷의 객체 변경 사항을 수신합니다.
예를 들어 썸네일 생성기 샘플은 프로젝트의 기본 버킷으로 범위가 지정됩니다.
exports.generateThumbnail = functions.storage.object().onFinalize(async (object) => { // ... });
Cloud Storage는 다음 이벤트를 지원합니다.
-
onArchive
버킷이 객체 버전 관리 를 활성화한 경우에만 전송됩니다. 이 이벤트는 객체의 라이브 버전이 보관되었거나 동일한 이름의 객체 업로드로 덮어써졌기 때문에 보관된 버전이 되었음을 나타냅니다. -
onDelete
개체가 영구적으로 삭제되었을 때 전송됩니다. 여기에는 버킷의 수명 주기 구성 의 일부로 덮어쓰거나 삭제된 객체가 포함됩니다. 객체 버전 관리 가 활성화된 버킷의 경우storage.objects.delete
메서드를 통해 보관이 발생하더라도 객체가 보관될 때(onArchive
참조) 전송되지 않습니다. -
onFinalize
새 객체(또는 기존 객체의 새로운 세대)가 버킷에 성공적으로 생성되면 전송됩니다. 여기에는 기존 객체 복사 또는 재작성이 포함됩니다. 실패한 업로드는 이 이벤트를 트리거하지 않습니다. -
onMetadataUpdate
기존 개체의 메타데이터가 변경될 때 전송됩니다.
onFinalize
에 대해 위에 표시된 대로 on
이벤트 핸들러 내에서 이벤트를 설정합니다.
Cloud Storage 개체 속성에 액세스
Cloud Functions는 업데이트된 파일의 size
및 contentType
과 같은 다양한 Cloud Storage 객체 속성을 노출합니다. 'metageneration' 속성은 개체의 메타데이터가 변경될 때마다 증가합니다. 새 개체의 경우 metageneration
값은 1
입니다.
const fileBucket = object.bucket; // The Storage bucket that contains the file. const filePath = object.name; // File path in the bucket. const contentType = object.contentType; // File content type. const metageneration = object.metageneration; // Number of times metadata has been generated. New objects have a value of 1.
썸네일 생성 샘플은 이러한 특성 중 일부를 사용하여 함수가 반환하는 종료 사례를 감지합니다.
// Exit if this is triggered on a file that is not an image. if (!contentType.startsWith('image/')) { return functions.logger.log('This is not an image.'); } // Get the file name. const fileName = path.basename(filePath); // Exit if the image is already a thumbnail. if (fileName.startsWith('thumb_')) { return functions.logger.log('Already a Thumbnail.'); }
파일 다운로드, 변환 및 업로드
경우에 따라 Cloud Storage에서 파일을 다운로드할 필요가 없을 수도 있습니다. 그러나 Cloud Storage에 저장된 파일에서 미리보기 이미지를 생성하는 것과 같은 집약적인 작업을 수행하려면 함수 인스턴스, 즉 코드를 실행하는 가상 머신에 파일을 다운로드해야 합니다.
개체를 Cloud Storage에 쉽게 다운로드하고 다시 업로드하려면 npm install --save @google-cloud/storage
를 사용하여 Google Cloud Storage 패키지 를 설치하고 가져옵니다. JavaScript Promise를 사용하여 샘플의 썸네일 처리 작업과 같은 외부 프로세스를 처리하려면 child-process-promise
도 가져옵니다.
const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp() const spawn = require('child-process-promise').spawn; const path = require('path'); const os = require('os'); const fs = require('fs');
gcs.bucket.file(filePath).download
를 사용하여 Cloud Functions 인스턴스의 임시 디렉터리에 파일을 다운로드합니다. 이 위치에서 필요에 따라 파일을 처리한 다음 Cloud Storage에 업로드할 수 있습니다. 비동기 작업을 수행할 때 콜백에서 JavaScript 약속을 반환하는지 확인하십시오.
예: 이미지 변환
Cloud Functions는 그래픽 이미지 파일을 조작할 수 있는 ImageMagick
이라는 이미지 처리 프로그램을 제공합니다. 다음은 업로드된 이미지 파일에 대한 썸네일 이미지를 생성하는 방법의 예입니다.
// Download file from bucket. const bucket = admin.storage().bucket(fileBucket); const tempFilePath = path.join(os.tmpdir(), fileName); const metadata = { contentType: contentType, }; await bucket.file(filePath).download({destination: tempFilePath}); functions.logger.log('Image downloaded locally to', tempFilePath); // Generate a thumbnail using ImageMagick. await spawn('convert', [tempFilePath, '-thumbnail', '200x200>', tempFilePath]); functions.logger.log('Thumbnail created at', tempFilePath); // We add a 'thumb_' prefix to thumbnails file name. That's where we'll upload the thumbnail. const thumbFileName = `thumb_${fileName}`; const thumbFilePath = path.join(path.dirname(filePath), thumbFileName); // Uploading the thumbnail. await bucket.upload(tempFilePath, { destination: thumbFilePath, metadata: metadata, }); // Once the thumbnail has been uploaded delete the local file to free up disk space. return fs.unlinkSync(tempFilePath);
이 코드는 ImageMagick
명령줄 프로그램 convert
을 실행하여 임시 디렉터리에 저장된 이미지의 200x200 미리보기 이미지를 만든 다음 다시 Cloud Storage에 업로드합니다.
더 많은 예 살펴보기
이미지 트랜스코딩 , 콘텐츠 조정 , EXIF 메타데이터 추출 을 포함한 일반적인 미디어 변환 기능의 더 많은 예. 예제의 전체 목록은 GitHub에서 확인할 수 있습니다.
자세한 내용은 전체 Google Cloud Storage 트리거 문서 를 참조하세요.