Uploading video to firebase - firebase

I am trying to upload videos to Firebase Storage using Angular2Fire and the Media Capture plugin. Everything is working as expected, but when I try to upload videos on a real Android device, the videos are being uploaded as an unknown type and are not functioning properly. Can anyone help me with this issue?
recordVideo() {
this.cam.captureVideo().then(
(data: MediaFile[]) => {
if (data.length > 0) {
let url = Capacitor.convertFileSrc(data[0].fullPath);
fetch(url).then(res => res.blob()).then(blob => {
const fileRef = this.afstorage.upload(`videos/${Date.now()}.mp4`, blob)
fileRef.then((res) => {
console.log(res);
this.api.loading('Upload Complete');
})
});
}
},
(err: CaptureError) => console.error(err)
);
}
ios working fine without any issue .

Related

Firebase remote config returning default value on android

I am using remote config in my react native project as following
useEffect(() => {
remoteConfig()
.setDefaults({
activation: 'project',
})
.then(() => remoteConfig().fetchAndActivate())
.catch(error => {
console.log(error)
})
.then(fetchedRemotely => {
if (fetchedRemotely) {
console.log('Configs were retrieved from the backend and activated.');
} else {
console.log('No configs were fetched from the backend, and the local configs were already activated',);
}
});
}, []);
var activation = remoteConfig().getValue('activation');
When I call activation.asString() in a function when a button is clicked, I first get the default value, not the one published. When I press cmd + s in the editor, the project is saved and the the get refreshed, then I start getting the remote value. And this happens only on android. I am implementing this correctly?

How do I fix firebase auth/netwok-request-failed when opened by social media browsers?

I recently had a bug to solve for a customer on my webapp. It is givng a
Firebase: Error(auth/network-request-failed)
However I also realize upon selecting 'Ok' on the alert, the browser redirects the user to login with their account, however has a my FIREBASE_AUTH_DOMAIN - {projectID}.firbaseapp.com .
This only occurs when user visit the login/signUp link via social media browser.
So I changed the signInWithPopUp -> signInWithRedirect.
And now I still get the error if I am redirected to the login/signUp page. How I do fix this?
const loginGoogle = async () => {
closeSnackbar();
const provider = new GoogleAuthProvider();
signInWithRedirect(auth, provider)
.then(() => {
createUserDoc(); //creates a userProfile document
enqueueSnackbar(
`Welcome ${
!auth.currentUser.displayName ? "" : auth.currentUser.displayName
}`,
{ variant: "success" }
);
})
.catch((error) => {
alert(error.message);
});
router.push(redirect || "/shop");
};

Error: storage/object-not-found when trying to upload large image file

I'm getting an error : storage/object-not-found when trying to upload a large image file in Google Cloud Storage using RxFire.
They say the image is not found in the bucket but when I check, i see them!
I tested with small images (100kb likely...) works great.
But tried with > 500kb images, doesn't work...
upload$
.pipe(
switchMap((event: any) => {
const name = Math.random().toString(36).substring(5);
const blob = event.target.files[0];
const type = blob.type.replace('image/', '');
const ref = storage.ref(`uploads/test/${name}.${type}`);
return put(ref, blob);
}),
map(snapshot => snapshot),
filter(snapshot => snapshot.totalBytes === snapshot.bytesTransferred),
mergeMap(snapshot => getDownloadURL(snapshot.ref))
)
.subscribe(url => {
console.log('Results', url)
}, (error) => {
// ERROR HERE
console.log('error', error)
})
Expected result : Upload working with big images
Actual results : Error
Uncaught t {code_: "storage/object-not-found", message_: "Firebase .
Storage: Object 'uploads/test/7xpbilmb.jpeg' does not exist.",
serverResponse_: "{↵ "error": {↵ "code": 404,↵ "message":
"Not Found. Could not get object"↵ }↵}", name_: "FirebaseError"}
You can do it both ways.
Promises
storageRef.put(blob, {customMetadata}).then(data => {
data.ref.getDownloadURL().then(url => {
// do whatever you want with url
});
});
Observables
downloadURL = new Subject();
this.downloadURL.pipe(
map(obs => obs),
concatAll()
).subscribe(url => {
// do whatever you want with url
});
let task = ref.put(blob, {customMetadata});
task.snapshotChanges().pipe(
finalize(() => this.downloadURL.next(ref.getDownloadURL()))
).subscribe();
This should be enough to get you your downloadURL. In case you wanna track upload progress with observables, here's the code for that:
task.percentageChanges().subscribe(progress => {
console.log('upload progress: ', progress);
if (res >= 100) {
// HOORAY!
}
});

Unable to create Dynamic Short link with React-native-firebase

I'm catching an error with code: "links/failure"
const link = new firebase.links.DynamicLink(
"LINK",
"firebaseDomainLink"
).android
.setPackageName("packagename")
.ios.setBundleId("bundleID");
firebase
.links()
.createShortDynamicLink(link, 'UNGUESSABLE')
.then(url => {
console.log(url)
})
.catch(err => {
console.warn(err);
});
However when using "createDynamicLink" I am able to get the long dynamic link as the return.
Tested with Android Platform
Picture of Yellow error box

Uploading Image to Firebase in React Native

I have two image paths in my component state
I try to upload one of the images inside of a function but get an error:
Firebase Storage: Invalid argument in 'put' at index 0: Expected Blob or file
and my function
submitImages = () => {
// Upload images to Firebase storage
let user = firebaseAuth.currentUser;
let imagesRef = storageRef.child('productImages/' + user.uid);
imagesRef.put(this.state.imageFront).then(snapshot => {
console.log('Uploaded ' + this.state.imageFront);
});
}
What should I be doing instead to get these images up to Firebase. Thanks!
What the error says is that you need to use a blob. You can use react-native-fetch-blob: https://github.com/wkh237/react-native-fetch-blob
Check out this example: https://github.com/dailydrip/react-native-firebase-storage/blob/master/src/App.js#L43-L69
I am posting my code since this was a bit frustrating for me:
To upload images to firebase.storage you need to upload the images as Blobs. If you don't know what Blobs are, don't worry: BLOB stands for Binary Large OBject.
Step 1.
npm install --save react-native-fetch-blob
Step 2.
// copy and paste this code where you will handle the file upload
import RNFetchBlob from 'react-native-fetch-blob'
const Blob = RNFetchBlob.polyfill.Blob;
const fs = RNFetchBlob.fs;
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest;
window.Blob = Blob;
Step 3.
// The uploadImage function that you are going to use:
function uploadImage(uri, mime = 'image/jpeg', name) {
return new Promise((resolve, reject) => {
let imgUri = uri; let uploadBlob = null;
const uploadUri = Platform.OS === 'ios' ? imgUri.replace('file://', '') : imgUri;
const { currentUser } = firebase.auth();
const imageRef = firebase.storage().ref(`/jobs/${currentUser.uid}`)
fs.readFile(uploadUri, 'base64')
.then(data => {
return Blob.build(data, { type: `${mime};BASE64` });
})
.then(blob => {
uploadBlob = blob;
return imageRef.put(blob, { contentType: mime, name: name });
})
.then(() => {
uploadBlob.close()
return imageRef.getDownloadURL();
})
.then(url => {
resolve(url);
})
.catch(error => {
reject(error)
})
})
}
So how do you call this function?
Pass the URI of the image as the first argument. In my case img1, img2, img3 where variables that pointed to the URIs of the images, that I wanted to upload which were on my phone. They looked something like '/Phone/Pics/imageToUpload.jpeg', etc.
As the second argument you can pass 'image/jpeg' and the last argument is the name that you want to give the image. Chose the name that you like.
But what if I have several images and want to upload them and want to handle the upload correctly. What if one upload succeeds and the other does not?
Do this then:
let imgPromises = [];
imgPromises.push(uploadImage(img1, 'image/jpeg', 'imageOne'));
imgPromises.push(uploadImage(img2, 'image/jpeg', 'imageTwo'));
imgPromises.push(uploadImage(img3, 'image/jpeg', 'imageOne'));
Promise.all(imgPromises).then(urls => {
// ALL IMAGES SUCCEEDED and you will get an array of URIS that you can save to your database for later use!
}).catch(error => {
// One OR many images failed the upload. Give feedback to someone.
})
You can use react-native-firebase to upload image to storge https://rnfirebase.io/
const storage = firebase.storage();
const sessionId = new Date().getTime();
const imageRef = storage.ref('images').child(`${sessionId}`);
return imageRef.putFile(uri);
So far this is the best method I found to upload a file/image to a Firebase Storage with React Native. This method does not use any third party libraries except for the Expo SDK.
Get the File URI of the image to upload. To do this we will need to use Expo ImagePicker. The best place to include this code block is on to a button with an onPress handler.
ImagePicker.launchImageLibraryAsync({
mediaTypes: "Images"
}).then((result)=>{
if (!result.cancelled) {
// User picked an image
const {height, width, type, uri} = result;
return uriToBlob(uri); // will follow later
}
})
Generate a BLOB from the image URI. There are a lot of third party libraries to help do this. But if you don't want to install a library, then you can use XMLHttpRequest. The React Native docs recommends we use the Fetch API, but right now we can't use it because it will throw an error that we can only fetch https:// urls, but our URI is a file://. There is a way to get pass this, but using XMLHttpRequest will make things a lot simpler.
uriToBlob = (uri) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function() {
// return the blob
resolve(xhr.response);
};
xhr.onerror = function() {
// something went wrong
reject(new Error('uriToBlob failed'));
};
// this helps us get a blob
xhr.responseType = 'blob';
xhr.open('GET', uri, true);
xhr.send(null);
});
}
We have our BLOB, let's upload it to Firebase. This part is pretty straightforward as explained in the Firebase Docs.
uploadToFirebase = (blob) => {
return new Promise((resolve, reject)=>{
var storageRef = firebase.storage().ref();
storageRef.child('uploads/photo.jpg').put(blob, {
contentType: 'image/jpeg'
}).then((snapshot)=>{
blob.close(); // let's free up the blob
resolve(snapshot);
}).catch((error)=>{
reject(error);
});
});
}
That's it, you can now upload a file to Firebase Storage. The key part to this is getting a File URI and converting it to a BLOB. You can read more about this method here.
For some time I used the Firebase JS SDK with React Native. Using this library, as referred in this thread you need to use a library like rn-fetch-blob (react-native-fetch-blob is not maintained anymore) in order to provide a blob to Firebase Storage put() method.
Recently I started using React Native Firebase. As they say in their website "Using the native Firebase SDKs with React Native Firebase allows you to consume device SDKs which don't exist on the Firebase JS SDK".
Using React-Native-Firebase you don't need any extra library to upload images to Firebase Storage, and your code gets much cleaner:
export const uploadImage = (path, mime = 'application/octet-stream') => {
return new Promise((resolve, reject) => {
const imageRef = firebase.storage().ref('images').child('filename.jpg');
return imageRef.put(path, { contentType: mime })
.then(() => {
return imageRef.getDownloadURL();
})
.then(url => {
resolve(url);
})
.catch(error => {
reject(error);
console.log('Error uploading image: ', error);
});
});
};
if you don’t mind using cloudinary, I show how to upload and then get the uploaded url to save to firebase
https://medium.com/#ifeoluwaking24/how-to-upload-an-image-in-expo-react-native-to-firebase-using-cloudinary-24aac981c87
Also you can try it snack but make sure you add your cloud_name and upload_preset
https://snack.expo.io/#ifeking/upload-to-cloudinary

Resources