This is the code which I use to upload images to firebase storage
JavaScript
x
12
12
1
const filename = image.substring(image.lastIndexOf('/') + 1);
2
const uploadUri = Platform.OS === 'ios' ? image.replace('file://', '') : image
3
var metadata = {
4
contentType: 'image/jpeg',
5
};
6
const task = firebase.storage().ref().put(uploadUri, metadata)
7
try {
8
await task
9
} catch(err) {
10
console.log(err)
11
}
12
But when I check the firebase console it shows, error loading preview, and the file size is 9B for a image. Is there something Im missing.
Im using Expo managed, expo-image-picker to select images.
Advertisement
Answer
I found a way, I had to create a blob and then upload the blob to firebase
JavaScript
1
34
34
1
const filename = image.substring(image.lastIndexOf('/') + 1);
2
3
const blob = await new Promise((resolve, reject) => {
4
const xhr = new XMLHttpRequest();
5
xhr.onload = function() {
6
resolve(xhr.response);
7
};
8
xhr.onerror = function() {
9
reject(new TypeError("Network request failed"));
10
};
11
xhr.responseType = "blob";
12
xhr.open("GET", image, true);
13
xhr.send(null);
14
});
15
const ref = firebase
16
.storage()
17
.ref()
18
.child(filename);
19
20
const task = ref.put(blob, { contentType: 'image/jpeg' });
21
22
task.on('state_changed',
23
(snapshot) => {
24
console.log(snapshot.totalBytes)
25
},
26
(err) => {
27
console.log(err)
28
},
29
() => {
30
task.snapshot.ref.getDownloadURL().then((downloadURL) => {
31
console.log(downloadURL);
32
});
33
})
34