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円のサブスクで質問し放題です
プログラミング学習や個人開発などに利用ください