Skip to content

Commit

Permalink
Added image upload component and backend call
Browse files Browse the repository at this point in the history
  • Loading branch information
ahong75 committed Sep 12, 2024
1 parent 467a440 commit d926d3a
Show file tree
Hide file tree
Showing 4 changed files with 289 additions and 0 deletions.
57 changes: 57 additions & 0 deletions web/components/BabyBook/ImageUpload.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import React, { useContext } from "react";
import { storage } from "../../db/firebase"; // import firebase storage
import { ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";

export const ImageUpload = ({}) => {
const saveFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
const files = e.target.files;
if (!files || files.length === 0) return;

try {
const file = files[0];

const extension = file.name.split(".").pop();
const storageRef = ref(storage, `images/${Date.now()}.${extension}`);

const uploadTask = uploadBytesResumable(storageRef, file);

uploadTask.on(
"state_changed",
(snapshot) => {
const progress =
(snapshot.bytesTransferred / snapshot.totalBytes) * 100;
},
(error) => {
console.error("Upload failed:", error);
},
async () => {
const downloadURL = await getDownloadURL(uploadTask.snapshot.ref);
// TODO: Incorporate baby and caregiver context
// https://github.com/GTBitsOfGood/motherhood-beyond-bars/blob/_original/mobile/screens/babybook/SelectPicture.tsx#L28
// TODO: Incorporate caption
const metadata = {
imageURL: downloadURL,
caregiverID: "test-caregiverId",
caption: "test-caption",
babyID: "test-babyId",
};
const response = await fetch("/api/save-image", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(metadata),
});
if (!response.ok) {
const result = await response.json();
alert(result.error || "Error uploading image metadata");
}
}
);
} catch (error) {
console.error("Upload failed:", error);
alert("An error occurred while uploading the image.");
}
};
return <input type="file" onChange={saveFile} />;
};
180 changes: 180 additions & 0 deletions web/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

38 changes: 38 additions & 0 deletions web/pages/api/save-image.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// pages/api/saveImage.js
import { NextApiRequest, NextApiResponse } from "next";
import { db } from "../../db/firebase"; // Firestore database
import { doc, setDoc, Timestamp } from "firebase/firestore";

export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method === "POST") {
// Extracting the necessary data from the request body
const { imageURL, caregiverID, caption, babyID } = req.body;

try {
// Create a reference to the document in the 'babies' collection and save metadata
const docRef = doc(
db,
"babies",
babyID,
"book",
`${caregiverID}_${Date.now()}`
);
await setDoc(docRef, {
imageUrl: imageURL,
caption: caption,
date: Timestamp.now(),
caregiverId: caregiverID,
});

res.status(200).json({ message: "Image metadata saved successfully" });
} catch (error) {
console.error("Error saving image metadata:", error);
res.status(500).json({ error: "Error saving image metadata" });
}
} else {
res.status(405).json({ message: "Method not allowed" });
}
}
14 changes: 14 additions & 0 deletions web/pages/upload-test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// pages/upload-test.js

import { ImageUpload } from "@components/BabyBook/ImageUpload";

const UploadTestPage = () => {
return (
<div>
<h1>Test Image Upload</h1>
<ImageUpload />
</div>
);
};

export default UploadTestPage;

0 comments on commit d926d3a

Please sign in to comment.