-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Image Upload Backend Endpoint (#132)
* Added image upload component and backend call * Clean and combine code --------- Co-authored-by: Parker Abramson <parkerrabramson@gmail.com>
- Loading branch information
Showing
1 changed file
with
64 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
import React from "react"; | ||
import { db, storage } from "../../firebase"; // import firebase storage | ||
import { ref, uploadBytesResumable, getDownloadURL } from "firebase/storage"; | ||
import { doc, setDoc, Timestamp } from "firebase/firestore"; | ||
|
||
export async function uploadPhoto(e: React.ChangeEvent<HTMLInputElement>) { | ||
const files = e.target.files; | ||
if (!files || files.length === 0) { | ||
return { success: false, error: "File attempted to be uploaded was empty" }; | ||
} | ||
|
||
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) => { | ||
return { success: false, 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 { imageURL, caregiverID, caption, babyID } = metadata; | ||
|
||
const docRef = doc( | ||
db, | ||
"babies", | ||
babyID, | ||
"book", | ||
`${caregiverID}_${Date.now()}` | ||
); | ||
|
||
await setDoc(docRef, { | ||
imageUrl: imageURL, | ||
caption: caption, | ||
date: Timestamp.now(), | ||
caregiverId: caregiverID, | ||
}); | ||
|
||
return { success: true, data: { downloadURL: downloadURL } }; | ||
} | ||
); | ||
} catch (error) { | ||
return { success: false, error: `Upload failed: ${error}` }; | ||
} | ||
} |