Cloud Storage 사용

Cloud Storage를 사용하여 영화, 이미지, 기타 정적 콘텐츠 등의 파일을 저장하고 제공할 수 있습니다.

이 문서는 앱에서 Google Cloud 클라이언트 라이브러리를 사용하여 Cloud Storage에 데이터를 저장하고 검색하는 방법을 설명합니다.

시작하기 전에

  • App Engine에서 Node.js용 'Hello, World!'의 안내에 따라 환경 및 프로젝트를 설정하고 App Engine에서 Node.js 앱이 구조화되는 방식을 알아봅니다. 이 문서에 설명된 샘플 애플리케이션을 실행할 때 필요하므로 프로젝트 ID를 기록해 둡니다.

  • 다음 명령어를 호출하여 애플리케이션용 Cloud Storage 버킷을 만듭니다.

    gsutil mb gs://[YOUR_BUCKET_NAME]
    
  • 공개 읽기 가능 버킷으로 만들어 파일을 제공할 수 있도록 합니다.

    gsutil defacl set public-read gs://[YOUR_BUCKET_NAME]
    

샘플 다운로드

저장소를 복제하려면 다음을 사용하세요.

git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples/
cd nodejs-docs-samples/appengine/storage/standard

프로젝트 구성 수정 및 종속 항목 설치

app.yaml에서 프로젝트 ID를 GOOGLE_CLOUD_PROJECT 환경 값에 추가합니다. 그런 다음 GCLOUD_STORAGE_BUCKET 환경 값을 이전에 만든 Cloud Storage 버킷의 이름으로 설정합니다.

runtime: nodejs16

env_variables:
  GCLOUD_STORAGE_BUCKET: YOUR_BUCKET_NAME

package.json에서 @google-cloud/storage를 종속 항목으로 추가합니다. 이 종속 항목은 Cloud Storage를 사용하기 위한 기능을 제공합니다.

{
  "name": "appengine-storage",
  "description": "Node.js Google Cloud Storage sample for Google App Engine",
  "scripts": {
    "start": "node app.js",
    "test": "mocha system-test/*.test.js --exit --timeout=30000"
  },
  "engines": {
    "node": ">=14.0.0"
  },
  "dependencies": {
    "@google-cloud/storage": "^6.0.0",
    "express": "^4.17.1",
    "multer": "^1.4.2",
    "pug": "^3.0.0"
  },
  "devDependencies": {
    "mocha": "^9.0.0",
    "supertest": "^6.0.0",
    "proxyquire": "^2.1.3"
  }
}

로컬에서 실행 및 테스트하는 방법은 README.md 파일을 참조하세요.

애플리케이션 코드

샘플 애플리케이션은 사용자에게 Cloud Storage에 저장할 파일을 제공하라는 메시지를 표시하는 웹페이지를 제공합니다. 사용자가 파일을 선택하고 제출을 클릭하면 업로드 핸들러가 파일 콘텐츠를 BLOB에 로드하고 이를 Cloud Storage에 작성합니다.

파일이 Cloud Storage에 업로드된 후에는 이 파일의 공개 URL이 반환되며, 이 URL을 사용하여 Cloud Storage에서 직접 파일을 제공할 수 있습니다. 나중에 사용할 수 있도록 이 값을 앱에 저장해야 합니다.

const {format} = require('util');
const express = require('express');
const Multer = require('multer');

// By default, the client will authenticate using the service account file
// specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use
// the project specified by the GOOGLE_CLOUD_PROJECT environment variable. See
// https://github.com/GoogleCloudPlatform/google-cloud-node/blob/master/docs/authentication.md
// These environment variables are set automatically on Google App Engine
const {Storage} = require('@google-cloud/storage');

// Instantiate a storage client
const storage = new Storage();

const app = express();
app.set('view engine', 'pug');

// This middleware is available in Express v4.16.0 onwards
app.use(express.json());

// Multer is required to process file uploads and make them available via
// req.files.
const multer = Multer({
  storage: Multer.memoryStorage(),
  limits: {
    fileSize: 5 * 1024 * 1024, // no larger than 5mb, you can change as needed.
  },
});

// A bucket is a container for objects (files).
const bucket = storage.bucket(process.env.GCLOUD_STORAGE_BUCKET);

// Display a form for uploading files.
app.get('/', (req, res) => {
  res.render('form.pug');
});

// Process the file upload and upload to Google Cloud Storage.
app.post('/upload', multer.single('file'), (req, res, next) => {
  if (!req.file) {
    res.status(400).send('No file uploaded.');
    return;
  }

  // Create a new blob in the bucket and upload the file data.
  const blob = bucket.file(req.file.originalname);
  const blobStream = blob.createWriteStream({
    resumable: false,
  });

  blobStream.on('error', err => {
    next(err);
  });

  blobStream.on('finish', () => {
    // The public URL can be used to directly access the file via HTTP.
    const publicUrl = format(
      `https://storage.googleapis.com/${bucket.name}/${blob.name}`
    );
    res.status(200).send(publicUrl);
  });

  blobStream.end(req.file.buffer);
});

const PORT = parseInt(process.env.PORT) || 8080;
app.listen(PORT, () => {
  console.log(`App listening on port ${PORT}`);
  console.log('Press Ctrl+C to quit.');
});

추가 정보

Cloud Storage에 대한 자세한 내용은 Cloud Storage 문서를 참조하세요.