Last active
March 1, 2023 23:02
-
-
Save Mr-emeka/533f36819d349999c85c0a410fb81b17 to your computer and use it in GitHub Desktop.
Image Upload to firebase using queue
This file contains hidden or 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
import { initializeApp } from "firebase/app"; | |
// Optionally import the services that you want to use | |
// import {...} from "firebase/auth"; | |
// import {...} from "firebase/database"; | |
// import {...} from "firebase/firestore"; | |
// import {...} from "firebase/functions"; | |
import { | |
getStorage, | |
ref, | |
uploadBytesResumable, | |
getDownloadURL, | |
} from "firebase/storage"; | |
// Initialize Firebase | |
const firebaseConfig = { | |
apiKey: "", | |
authDomain: "", | |
projectId: "", | |
storageBucket: "", | |
messagingSenderId: "", | |
appId: "", | |
measurementId: "", | |
}; | |
const app = initializeApp(firebaseConfig); | |
const storage = getStorage(app); | |
const uploadQueue = []; | |
let isUploading = false; | |
export const processUploadQueue = async () => { | |
if (isUploading) return; | |
isUploading = true; | |
const urls = []; | |
while (uploadQueue.length) { | |
const { file, name } = uploadQueue[0]; | |
try { | |
const url = await upload(file); | |
console.log(url); | |
urls.push({ [name]: url }); | |
} catch (err) { | |
console.log(err); | |
} | |
uploadQueue.shift(); | |
} | |
isUploading = false; | |
return urls; | |
}; | |
export const enqueueUpload = (file, name) => { | |
uploadQueue.push({ file, name }); | |
// processUploadQueue(); | |
}; | |
export const upload = (file) => { | |
return new Promise(async (resolve, reject) => { | |
try { | |
const blob = await new Promise((resolve, reject) => { | |
const xhr = new XMLHttpRequest(); | |
xhr.onload = function () { | |
resolve(xhr.response); | |
}; | |
xhr.onerror = function () { | |
reject(new TypeError("Network request failed")); | |
}; | |
xhr.responseType = "blob"; | |
xhr.open("GET", file, true); | |
xhr.send(null); | |
}); | |
const storageRef = ref(storage, `/files/image`); | |
const uploadTask = uploadBytesResumable(storageRef, blob); | |
uploadTask.on( | |
"state_changed", | |
(snapshot) => { | |
const percent = Math.round( | |
(snapshot.bytesTransferred / snapshot.totalBytes) * 100 | |
); | |
console.log(percent); | |
}, | |
(err) => { | |
blob.close(); | |
reject(err); | |
}, | |
() => { | |
getDownloadURL(uploadTask.snapshot.ref) | |
.then((url) => { | |
// console.log(url); | |
blob.close(); | |
resolve(url); | |
}) | |
.catch((err) => { | |
blob.close(); | |
reject(err); | |
}); | |
} | |
); | |
} catch (err) { | |
reject(err); | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
first add image to queue
process added images