LoginSignup
18
18

More than 5 years have passed since last update.

CloudFunctionsからCloudStorageへ画像をアップロードする

Last updated at Posted at 2019-01-30
async function createPhoto(data: string) {
  try {
    const base64EncodedImageString = data.replace(
      /^data:image\/\w+;base64,/,
      '',
    )
    const imageBuffer = Buffer.from(base64EncodedImageString, 'base64')
    const file = admin
      .storage()
      .bucket()
      .file(`${cloudStoragePhotoPath}/test.jpg`)
    await file.save(imageBuffer, { metadata: { contentType: 'image/jpeg' } })
    const url = await file.getSignedUrl({
      action: 'read',
      expires: '01-01-2099',
    })
    return url
  } catch (e) {
    throw e
  }
}

何をやってるのか

CloudFunctionsなので、どこかにあるファイルから画像は読み込めない。なのでbase64でCloudFunctionsへ画像を送る前提。

データをBufferにする

    const base64EncodedImageString = data.replace(
      /^data:image\/\w+;base64,/,
      '',
    )
    const imageBuffer = Buffer.from(base64EncodedImageString, 'base64')

ここでデータをBufferに。エンコーディング時の識別子があれば、replaceでそれを消す。

ファイルの作成

    const file = admin
      .storage()
      .bucket()
      .file(`${cloudStoragePhotoPath}/test.jpg`)

ここでCloudStorage上にファイルを作成。この時点ではファイルのデータはここに書き込まれていない。

参考: https://cloud.google.com/nodejs/docs/reference/storage/2.3.x/File

    await file.save(imageBuffer, { metadata: { contentType: 'image/jpeg' } })

save() でやっとファイルにデータを書き込む。コンテントタイプもここで忘れずに指定。

URLの取得

    const url = await file.getSignedUrl({
      action: 'read',
      expires: '01-01-2099',
    })

これで公開用のトークン付きURLを取得できる。トークンさえあれば基本誰でも画像にアクセスできる。actionをwriteにすれば、このURLにPOSTすることで画像の上書きをもできるとのこと。普通の使い方ではないけど、そういう用途で使ってみるのも面白いのかも。

18
18
3

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
18
18