I'm uploading a camera picture to a Firebase Storage bucket. When its done, i retrieve the image-url to display it in my view. The current Coding looks like this:
takePicture() {
this.camera.getPicture(this.cameraOptions)
.then(data => {
let base64Image = 'data:image/jpeg;base64,' + data;
let storageRef = firebase.storage().ref();
let imageName = this.imageSrv.generateUUID();
let imageRef = storageRef.child(`${this.afAuth.auth.currentUser.uid}/${imageName}.jpg`);
imageRef.putString(base64Image, 'data_url').then(data => {
imageRef.getDownloadURL().then(data => { this.url = data.toString(); })
}
)
});
}
It works, but it is not really great. I would like to put the coding to handle the database into a provider. How can this be achieved when using promises on the firebase storage? I cant directly access and return the URL in the providers methods because of the async handling:
getURL( userID: string, imageName: string) {
let storageRef = firebase.storage().ref();
let imageRef = storageRef.child(`${userId}/${imageId}.jpg`);
return imageRef.getDownloadURL();
}
I would also like to do this for N images to view an image gallery.
Thank you in advance.
Related
I am creating an app using firebase and react.js. When I reload the app, only the very last image shows up, when instead all of them should be loaded on the first page. Here is my handleUpload function where the issue lies (Updated):
const handleUpload = () => {
//const storageRef = ref(storage, `images/${image.name}`);
const randomId = doc(collection(db, "temp")).id;
const storageRef = ref(storage, `images/${randomId}`);
const uploadTask = uploadBytesResumable(storageRef, image);
uploadTask.on(
"state_changed",
(snapshot) => {
//Progress function ... (shows the load bar)
const progress = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
);
setProgress(progress);
},
(error) => {
//Error Function...
console.log(error);
alert(error.message);
},
async () => {
//complete function
const url = await getDownloadURL(storageRef);
const docRef = await addDoc(collection(db, "posts"), {
imageURL: url,
caption: caption,
username: username,
timestamp: serverTimestamp()
});
console.log("THE APP HAS POSTED");
setProgress(0);
setCaption('');
setImage(null);
setUrl('');
}
)
}
Here is my storage console after restarting and posting 2 photos from an iPhone:
There should be 2 photos there, but only the latest one shows up, with the name ${image.name}, which I don't understand because I have that line commented out.
Note: this issue only occurs when someone uploads on a phone since there are no file names on a phone, just a picture from a camera roll. Is there a way to fix this that anyone can think of?
Firebase storage doesn't generate a random ID for new files. You must specify then file name while uploading it. You can use a package like UUID or even Firestore to generate random IDs as shown below:
const randomId = doc(collection(db, "temp")).id
const storageRef = ref(storage, `images/${randomId}`);
Also make sure you add the file extension at the end of filename.
Are you trying to upload image with same name? In that case it'll overwrite the existing image with that name.
This question already has answers here:
ReactJS: Resize image before upload
(4 answers)
Closed 1 year ago.
My following code for uploading an image to firebase storage is working properly.
But I want to reduce the file size of "file1 (The image)" to 100px*100px. And upload it to firebase storage.
function uploadImage() {
const ref = firebase.storage().ref();
const file1 = document.querySelector("#photo").files[0];
const metadata = {
contentType: file1.type
};
const task = ref.child(mydata.uid).put(file1, metadata);
task
.then(snapshot => snapshot.ref.getDownloadURL())
.then(url => {
db.collection('user').doc(mydata.docid).update({
profilepic : url,
});
const image = document.querySelector("#image")
image.src = url;
alert("uploaded")
})
.catch(console.error);
}
Please provide the full code for uploading a resized image to the firebase storage.
As your question appears to be for React, there is an npm package that does exactly this: React Image Resizer
After you wrap the resizer as outlined in the npm package documentation, you'll modify your code to be as follows:
async function uploadImage() {
const ref = firebase.storage().ref();
const file1 = document.querySelector("#photo").files[0];
const resizedImg = await resizeFile(file1);
const metadata = {
contentType: file1.type
};
const task = ref.child(mydata.uid).putString(resizedImg, 'base64', metadata);
task
.then(snapshot => snapshot.ref.getDownloadURL())
.then(url => {
db.collection('user').doc(mydata.docid).update({
profilepic : url,
});
const image = document.querySelector("#image")
image.src = url;
alert("uploaded")
})
.catch(console.error);
}
I want to save images in Firebase Storage with its own name.....
so, this is my uploading code..
storage.ref('users/'+ imgId + "/post.jpg").put(file).then(function () {
console.log("uploaded");
and this is my retrieval code..
storage.ref('users/'+ user.uid + "/post.jpg").getDownloadURL().then(img => {
postImage = img
}).catch(error => {
console.log(error);
})
Whats happening is that when ever I upload a new image it overrides the older image and also overrides the image in UI. can anyone has a solution ?
By using storage.ref('users/'+ user.uid + "/post.jpg").put(file) you are uploading the file as users/USER_ID/post.jpg.
If the intention is to upload a "primary" image for a particular post, instead save the image as posts/POST_ID/main.jpg (hard to trace author) or users/USER_ID/images/POST_ID-main.jpg (easy to trace author).
// for "users/USER_ID/images/POST_ID-main.jpg"
const postImageRef = storage
.ref('users/'+ user.uid + "/images/" + postId + "-main.jpg");
// OR
// for "users/USER_ID/images/POST_ID-main.jpg"
const postImageRef = storage
.ref('users/'+ user.uid)
.child("images")
.child(postId + "-main.jpg");
// OR
// for "posts/POST_ID/main.jpg"
const postImageRef = storage
.ref('posts/'+ postId)
.child(main.jpg");
postImageRef.put(file)
.then(() => {
console.log("uploaded");
return postImageRef.getDownloadURL();
})
.then((imageURL) => {
// TODO: use imageURL
})
As you seem to be setting a variable postImage from inside the promise, you are going to run into race conditions. To avoid that, switch to async/await syntax like so:
// elsewhere
const POSTS_REF = database.ref('posts');
const newPostRef = POSTS_REF.push();
const postId = newPostRef.key;
const postImageStorageRef = storage
.ref('users/'+ user.uid)
.child("images")
.child(postId + "-main.jpg");
await postImageStorageRef.put(file);
console.log("uploaded");
const postImage = await postImageStorageRef.getDownloadURL();
// do something with postImage
await newPostRef
.set({
image: postImage,
uid: user.uid,
...
});
console.log("Created post #" + postId);
i have a bunch of VHD files stored on a private Server, which are accessible through a url.
I am trying upload these vhd files directly to my azure storage account using the azure javascript npm libraries. The vhds have to be uploaded as page-blobs. I tried using the method uploadPagesFromURL() of the pageblobClient but with no success. My code looks roughly like this:
async function uploadVHD(accessToken, srcUrl)
{
try {
// Get credentials from accessToken
const creds = new StorageSharedKeyCredential(storageAccount.name, storageAccount.key);
// Get blobServiceClient
const blobServiceClient = new BlobServiceClient(`https://${storageAccount.name}.blob.core.windows.net`, creds);
// Create Container
const containerClient = blobServiceClient.getContainerClient("vhd-images");
await containerClient.createIfNotExists();
const src = srcUrl.replace('https://', 'https://username:password#');
// Upload to blob storage
const pageBlobClient = containerClient.getPageBlobClient("Test.vhd");
// Get fileSize of vhd
const fileSize = (await axiosRequest(src, { method: "HEAD" })).headers["content-length"];
const uploadResponse = await pageBlobClient.uploadPagesFromURL(src, 0, 0, fileSize);
return uploadResponse;
} catch (error) {
return error;
}
});
It is not possible to upload the Page Blob with your URL directly. You need to read data from the url. Then upload using uploadPages method.
axios.get(URL, {
responseType: 'arraybuffer'
})
.then((response) => {
console.log(response.data)
console.log(response.data.length)
// upload page blob...
}).catch((error) => {
//handle error
});
// uploadPages method
const uploadResponse = pageBlobClient.uploadPages(data, 0, dataLength);
I used react-native-firebase lib in my RN App
and I use Firebase Storage to save image in the cloud so it's work very well but
In profile screen and I have an Edit function that replaces the old image with a new one but it's just adding a new image to Firebase Cloud Storage not replaced it
so there any way for just replacing old with new?
because I don't want to increase my storage when users change his image profile
here is my function that's save new image profile
EditImg = async () => {
const {uid, avatar} = this.state;
let providerRef = database().ref(`Providers/users/${uid}`);
const path = 'Avatar_' + new Date().getTime() + '.jpg';
const ref = storage().ref(`providers/${uid}/providerGalary/${path}`);
await ref.putFile(avatar).then(() => {
ref.getDownloadURL().then(
img => {
console.log('img', img);
providerRef
.update({
avatar: img,
})
.then(() => console.log('saved to Db Successfully'));
},
error => console.log(error),
);
});
};
Change this:
const path = 'Avatar_' + new Date().getTime() + '.jpg';
const ref = storage().ref(`providers/${uid}/providerGalary/${path}`);
await ref.putFile(avatar).then(() => {
Into this:
const path = 'Avatar_' + uid + '.jpg';
const ref = storage().ref(`providers/${uid}/providerGalary/${path}`);
await ref.putFile(avatar).then(() => {
Use the uid instead of new Date, since the uid will stay the same thus you will be able to replace the image instead of adding a new one