728x90

Google Cloud에 Node.js를 사용하여 이미지를 저장하려면 Google Cloud Storage를 사용할 수 있습니다. Google Cloud Storage는 대용량의 데이터를 저장하고 관리할 수 있는 서비스입니다. 다음은 Node.js를 사용하여 이미지를 Google Cloud Storage에 업로드하는 기본적인 방법을 설명합니다.

1. Google Cloud 프로젝트 설정

  1. Google Cloud Console에 로그인합니다.
  2. 프로젝트를 생성하거나 기존 프로젝트를 선택합니다.
  3. Google Cloud Storage API를 활성화합니다.
  4. 서비스 계정을 생성하고 JSON 형식의 키 파일을 다운로드합니다. 이 파일은 Node.js 애플리케이션에서 인증에 사용됩니다.

2. Node.js 프로젝트 설정

  1. Node.jsnpm이 설치되어 있어야 합니다. 프로젝트 디렉터리를 생성하고 초기화합니다.

     mkdir my-cloud-storage-app
     cd my-cloud-storage-app
     npm init -y
  2. 필요한 패키지를 설치합니다.

     npm install @google-cloud/storage multer
    • @google-cloud/storage: Google Cloud Storage의 Node.js 클라이언트 라이브러리
    • multer: Express에서 파일 업로드를 처리하는 미들웨어

3. 코드 작성

index.js 파일을 생성하고 다음 코드를 추가합니다:

const express = require('express');
const multer = require('multer');
const { Storage } = require('@google-cloud/storage');
const path = require('path');

// Google Cloud Storage 설정
const storage = new Storage({
  keyFilename: 'path/to/your-service-account-file.json'
});
const bucketName = 'your-bucket-name';
const bucket = storage.bucket(bucketName);

// Express 앱 설정
const app = express();
const port = 3000;

// Multer 설정
const multerStorage = multer.memoryStorage();
const upload = multer({ storage: multerStorage });

app.post('/upload', upload.single('image'), async (req, res) => {
  if (!req.file) {
    return res.status(400).send('No file uploaded.');
  }

  const { originalname, buffer } = req.file;
  const blob = bucket.file(originalname);
  const blobStream = blob.createWriteStream({
    metadata: {
      contentType: req.file.mimetype,
    },
  });

  blobStream.on('error', (err) => {
    console.error(err);
    return res.status(500).send(err.message);
  });

  blobStream.on('finish', () => {
    const publicUrl = `https://storage.googleapis.com/${bucketName}/${originalname}`;
    res.status(200).send(`File uploaded successfully. Access it at: ${publicUrl}`);
  });

  blobStream.end(buffer);
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

4. 테스트

  1. 서버 실행:

     node index.js
  2. 파일 업로드 테스트: Postman이나 curl을 사용하여 http://localhost:3000/upload로 POST 요청을 보냅니다. image라는 필드 이름으로 이미지를 첨부합니다.

5. 주의사항

  • 서비스 계정 키 파일의 경로를 정확히 지정해야 합니다.
  • 버킷 이름을 정확히 설정해야 합니다.
  • 업로드된 파일은 공개 접근이 필요할 수 있습니다. 적절한 권한을 설정하거나, 파일을 공개적으로 설정할 수 있습니다.

이제 Google Cloud Storage에 Node.js를 사용하여 이미지를 업로드할 수 있습니다! 추가적인 질문이 있다면 언제든지 물어보세요.

728x90
반응형

+ Recent posts