Skip to content

Instantly share code, notes, and snippets.

@faustoct1
Last active June 14, 2022 05:12
Show Gist options
  • Save faustoct1/96c06571a442746bc8d1d398b5eca174 to your computer and use it in GitHub Desktop.
Save faustoct1/96c06571a442746bc8d1d398b5eca174 to your computer and use it in GitHub Desktop.
A simple code to save media (image/video) of remote source or local to firebase storage
/*
Those imports are to react-native-firebase and firebase storage.
If you use other client stuff, you must to replace the imports
by the include/imports of your languange
or framework, as well as the respective calls.
*/
// START ----
import firebase from '@react-native-firebase/app'
import '@react-native-firebase/storage'
const storage = firebase.storage()
// END ----
import { v4 as uuid } from 'uuid'
const saveMediaToStorage = async (id,url) => {
try{
const reference = storage.ref(`${id}/${uuid.v4()}`)
if(url.startsWith('http')){//remote image
const resp = await fetch(url)
const blob = await resp.blob()
await reference.put(blob)
} else { //local image
await reference.putFile(url)
}
return await reference.getDownloadURL()
} catch(e){
console.log('something went wrong',e)
}
return null
}
/*
How to use it:
testId: the folder to be created in storage that'll store the media
url: the path to local file or the url
...
await saveMediaToStorage('testId',SOME_URL_HERE) //from internet
await saveMediaToStorage('testId',LOCAL_PATH_TO_FILE_HERE) //local file
...
reference.getDownloadURL() returns the url to access
the uploaded media in firebase storage
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment