0
1

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.

Firebase Storageにてmetadataがうまく適応されない場合の対応

Last updated at Posted at 2021-12-08

NG

const storage = getStorage();
const storageRef = ref(storage, 'images/mountains.jpg');

const metadata = {
  contentType: 'image/jpeg',
  'location': 'Yosemite, CA, USA',
  'activity': 'Hiking'
};

uploadBytes(storageRef, image as Blob, metadata);

OK

const storage = getStorage();
const storageRef = ref(storage, 'images/mountains.jpg');

const metadata = {
  contentType: 'image/jpeg',
  customMetadata: {
    'location': 'Yosemite, CA, USA',
    'activity': 'Hiking'
  }
};

uploadBytes(storageRef, image as Blob, metadata);

公式ドキュメント:
https://firebase.google.com/docs/storage/web/file-metadata?hl=ja#custom_metadata

検証のために利用したベースコードメモ:
https://codesandbox.io/s/thyb0?file=/pages/index.js

上記コードをNext.js用に書き換えた検証コード:

import { useState } from 'react'
import type { ChangeEvent, MouseEvent } from 'react'
import type { NextPage } from 'next'
import { getStorage, ref, uploadBytes } from "firebase/storage"

const Privacy: NextPage = () => {
  const [image, setImage] = useState<File>();
  const [createObjectURL, setCreateObjectURL] = useState<string>();

  const uploadToClient = (event: ChangeEvent<HTMLInputElement>) => {
    if (event.target.files && event.target.files[0]) {
      const I = event.target.files[0];

      setImage(i);
      setCreateObjectURL(URL.createObjectURL(i));
    }
  };

  const uploadToServer = async (event: MouseEvent<HTMLButtonElement>) => {
    const body = new FormData();
    
    const storage = getStorage();
    const storageRef = ref(storage, 'images/mountains.jpg');

    const metadata = {
      contentType: 'image/jpeg',
      customMetadata: {
        'location': 'Yosemite, CA, USA',
        'activity': 'Hiking'
      }
    };

    uploadBytes(storageRef, image as Blob, metadata);
  };

  return (
    <div>
      <div>
        <img src={createObjectURL!} />
        <h4>Select Image</h4>
        <input type="file" name="myImage" onChange={uploadToClient} />
        <button
          className="btn btn-primary"
          type="submit"
          onClick={uploadToServer}
        >
          Send to server
        </button>
      </div>
    </div>
  );
}

export default Privacy

\プログラミング相談Slackコミュニティやってます/

月額9,800円のサブスクで質問し放題です
プログラミング学習や個人開発などに利用ください

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?