3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Node.js】GoogleCloudStorage(GCS)に画面から受け取ったファイルをアップロードする

Posted at

概要

Node.jsでGoogleCloudStorage(GCS)にアップロードする際に、サーバに配置されてるファイルをアップロードする実装サンプルはけっこう見つけられたのですが、
画面経由で受け取ったファイルを、GCSにアップロードする実装があまり無かったので、今回メモ書きします。

前提

実装サンプル

import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import {
  Storage as Gcs,
  Bucket,
} from '@google-cloud/storage';

@Injectable()
export class FileUploadService {
  constructor(private configService: ConfigService) {}

  getGcsBucket(): Bucket {
    // 環境の設定ファイルから認証用のキーファイルとバケット名を取得
    const storage = new Gcs({
      keyFilename: this.configService.get<string>('GOOGLE_SECRETS_FILE'),
    });
    return storage.bucket(
      this.configService.get<string>('GOOGLE_STORAGE_BUCKET'),
    );
  }

  // 画面から受け取ったファイルとアップロード先のパスを引数に設定
  addFileToGcs(uploadFile: Express.Multer.File, uploadPath: string): Promise<string> {
    return new Promise((resolve) => {
      const bucketFile = this.getGcsBucket().file(uploadPath);
      const stream = bucketFile.createWriteStream({
        metadata: {
          contentType: uploadFile.mimetype,
        },
      });

      stream.on('error', (err) => {
        throw err;
      });

      stream.on('finish', async () => {
        bucketFile.makePublic().then(() => {
          resolve(bucketFile.publicUrl());
        });
      });
      // ファイルからBufferを取得
      stream.end(uploadFile.buffer);
    });
  }
}
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?