Upload base64 Image to Firebase React native - javascript

I try to upload a "base64" image to Firebase by using React Native on iOS. But when I try to upload the image, I get following error:
undefined is not an object (evaluating 'uri.substring')
I get my image by using route.params and if I display the image in a view like this, the image is displayed.
<Image style={styles.image} source={{ uri: `data:image/png;base64,${myImage}` }}/>
Should I do anything else if the image is in "base64" or what else should I do?
This is my code:
// Here is how I get the image
const { myImage } = props.route.params;
const uploadImage = async () => {
const {uri} = myImage;
const filename = uri.substring(uri.lastIndexOf('/') + 1);
const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri;
setUploading(true);
setTransferred(0);
const task = storage()
.ref(filename)
.putFile(uploadUri);
// set progress state
task.on('state_changed', snapshot => {
setTransferred(
Math.round(snapshot.bytesTransferred / snapshot.totalBytes) * 10000
);
});
try {
await task;
} catch (e) {
console.error(e);
}
setUploading(false);
Alert.alert(
'Photo uploaded!',
'Your photo has been uploaded to Firebase Cloud Storage!'
);
};

Looking at your current code, you take myImage out of props.route.params, and this is a string of Base 64 characters corresponding to a PNG image (such as iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAMSURBVBhXY/j//z8ABf4C/qc1gYQAAAAASUVORK5CYII= - the data of a PNG for a single #FFFFFF pixel).
const { myImage } = props.route.params;
Below that you try to get a property uri out of this myImage string. As this property doesn't exist, you will get undefined. This uri = undefined value then throws an error on the next line.
const { uri } = myImage; // uri is undefined! ("".uri === undefined)
const filename = uri.substring(uri.lastIndexOf('/') + 1); // throws error!
The correct way to upload a Data URL would be to use the Reference#putString() method as covered in the documentation here.
Applying this to your code, you would use:
const { myImage } = props.route.params;
const uploadImage = async () => {
const dataUrl = `data:image/png;base64,${myImage}`;
// you could use a Firestore Doc ID, a RTDB Push ID or
// some `uuid` implementation to generate a suitable filename.
const storageRef = storage()
.ref(/* provide a path for the image */);
const uploadTask = storageRef
.putString(dataUrl, 'data_url');
uploadTask.on('state_changed', snapshot => {
setTransferred(
Math.round(snapshot.bytesTransferred / snapshot.totalBytes) * 10000
);
});
try {
await uploadTask;
setUploading(false);
Alert.alert(
'Photo uploaded!',
'Your photo has been uploaded to Firebase Cloud Storage!'
);
} catch (err) {
// TODO: Check value of `err.code` and handle appropriately.
console.error('Upload failed: ', err);
Alert.alert(
'Photo upload failed!',
'Your photo didn\'t upload properly!'
);
}
}
To prevent overwriting someone else's data and make security rules easier to implement, you should prefix the uploaded file with the user's ID similar to:
const storageRef = storage()
.ref('userUploads')
.child(firebase.auth().currentUser.uid)
.child(/* generated image ID */);
// builds a reference to /userUploads/someUserId/someImageId

If your image data string looks something like this:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABQAAAALQCAYAAADPfd1WAAAAAXNSR0IArs4c6QAAIABJREFUeF7svXmPLEly4GcRkVnnO/r1656+5uRcJEGAnMEO ...
Then you can use the putString method - but you need to remove the starting info data:image/png;base64, first.
await storage.ref("pictures/thumbnail.png").putString(thumbnailImageData.split("data:image/png;base64,")[1], "base64");

Related

Firebase storage, new image upload doesn't have a unique name

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.

Firebase v9 uploading image shows only 9 bytes

im using react native and firebase (v9) to upload image to firebase. in the firebase storage, the file was uploaded, but the size is only 9 bytes so it's not opening properly. I'm not sure how to fix this :S
const uploadFiles = (file, name, storeKey) => {
if(!file){
console.log('no file exists')
return;
}
const exe = file.substring(file.lastIndexOf('.'));
const fileName = name + exe;
const storageRef = ref(storage, `/files/${fileName}`);
const uploadTask = uploadBytesResumable(storageRef, file);
uploadTask.on('state_changed', null,
(error) => {
alert(error);
},
() => {
getDownloadURL(uploadTask.snapshot.ref)
.then((URL) => {
setDoc(doc(db, 'Store', storeKey, 'coffeeDB', name), {postImage: URL}, {merge: true});
console.log('url registered')
});
}
)
}
Given that you're calling file.substring(...), it seems that file is a file name. You can't upload a file by just passing its name, as that'd be a security risk. Instead you'll need to pass a Blob | Uint8Array | ArrayBuffer as shown here and here, typically by passing the File reference from which you got the file name.

Upload .vhd as Page-Blob to azure-blob-storage from Url

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);

Firebase Cloud Function Too Slow

I have a cloud function that receives the uid of an image and associate it to the user who calls it after validating its dimensions and generate its thumbnail. It looks simple but I have to wait around 40 seconds to see the results, and sometimes it gets congested or something and I have to call the function again to see previous results.
Has anyone experience it before? How can I fix that?
exports.validateImageDimensions = functions
.region("us-central1")
.runWith({ memory: "2GB", timeoutSeconds: 120 })
.https.onCall(async (data, context) => {
As you can see the CPU used is high...
Thanks.
UPDATE
Code of the function:
exports.validateImageDimensions = functions
.region("us-central1")
.runWith({ memory: "2GB", timeoutSeconds: 120 })
.https.onCall(async (data, context) => {
// Libraries
const admin = require("firebase-admin");
const sizeOf = require("image-size");
const url = require("url");
const https = require("https");
const sharp = require("sharp");
const path = require("path");
const os = require("os");
const fs = require("fs");
// Lazy initialization of the Admin SDK
if (!is_validateImageDimensions_initialized) {
admin.initializeApp();
is_validateImageDimensions_initialized = true;
}
// Create Storage
const storage = admin.storage();
// Create Firestore
const firestore = admin.firestore();
// Get the image's owner
const owner = context.auth.token.uid;
// Get the image's info
const { id, description, location, tags } = data;
// Photos's bucket
const bucket = storage.bucket("bucket");
// File Path
const filePath = `photos/${id}`;
// Get the file
const file = getFile(filePath);
// Check if the file is a jpeg image
const metadata = await file.getMetadata();
const isJpgImage = metadata[0].contentType === "image/jpeg";
// Get the file's url
const fileUrl = await getUrl(file);
// Get the photo dimensions using the `image-size` library
https.get(url.parse(fileUrl), (response) => {
let chunks = [];
response
.on("data", (chunk) => {
chunks.push(chunk);
})
.on("end", async () => {
// Check if the image has valid dimensions
let dimensions = sizeOf(Buffer.concat(chunks));
// Create the associated Firestore's document to the valid images
if (isJpgImage && hasValidDimensions(dimensions)) {
// Create a thumbnail for the uploaded image
const thumbnailPath = await generateThumbnail(filePath);
// Get the thumbnail
const thumbnail = getFile(thumbnailPath);
// Get the thumbnail's url
const thumbnailUrl = await getUrl(thumbnail);
try {
await firestore
.collection("posts")
.doc(owner)
.collection("userPosts")
.add({
id,
uri: fileUrl,
thumbnailUri: thumbnailUrl, // Useful for progress images
description,
location,
tags,
date: admin.firestore.FieldValue.serverTimestamp(),
likes: [], // At the first time, when a post is created, zero users has liked it
comments: [], // Also, there aren't any comments
width: dimensions.width,
height: dimensions.height,
});
// TODO: Analytics posts counter
} catch (err) {
console.error(
`Error creating the document in 'posts/{owner}/userPosts/' where 'id === ${id}': ${err}`
);
}
} else {
// Remove the files that are not jpeg images, or whose dimensions are not valid
try {
await file.delete();
console.log(
`The image '${id}' has been deleted because it has invalid dimensions.
This may be an attempt to break the security of the app made by the user '${owner}'`
);
} catch (err) {
console.error(`Error deleting invalid file '${id}': ${err}`);
}
}
});
});
/* ---------------- AUXILIAR FUNCTIONS ---------------- */
function getFile(filePath) {
/* Get a file from the storage bucket */
return bucket.file(filePath);
}
async function getUrl(file) {
/* Get the public url of a file */
const signedUrls = await file.getSignedUrl({
action: "read",
expires: "01-01-2100",
});
// signedUrls[0] contains the file's public URL
return signedUrls[0];
}
function hasValidDimensions(dimensions) {
// Posts' valid dimensions
const validDimensions = [
{
width: 1080,
height: 1080,
},
{
width: 1080,
height: 1350,
},
{
width: 1080,
height: 750,
},
];
return (
validDimensions.find(
({ width, height }) =>
width === dimensions.width && height === dimensions.height
) !== undefined
);
}
async function generateThumbnail(filePath) {
/* Generate thumbnail for the progressive images */
// Download file from bucket
const fileName = filePath.split("/").pop();
const tempFilePath = path.join(os.tmpdir(), fileName);
const thumbnailPath = await bucket
.file(filePath)
.download({
destination: tempFilePath,
})
.then(() => {
// Generate a thumbnail using Sharp
const size = 50;
const newFileName = `${fileName}_${size}_thumb.jpg`;
const newFilePath = `thumbnails/${newFileName}`;
const newFileTemp = path.join(os.tmpdir(), newFileName);
sharp(tempFilePath)
.resize(size, null)
.toFile(newFileTemp, async (_err, info) => {
// Uploading the thumbnail.
await bucket.upload(newFileTemp, {
destination: newFilePath,
});
// Once the thumbnail has been uploaded delete the temporal file to free up disk space.
fs.unlinkSync(tempFilePath);
});
// Return the thumbnail's path
return newFilePath;
});
return thumbnailPath;
}
});
Pd: In the console I can read this record:
"Function execution took 103 ms, finished with status code: 200"
but I have to wait, as I said before, around 40 seconds to see the new doc on my firestore
You're not dealing with promises correctly. A callable function must return a promise that:
Resolves when all of the async work is complete
Resolves with the data to send back to the client
Right now, your function returns nothing, so it returns to the caller immediately, and the future of the async work that you kicked off is uncertain.
Note that https.get() is asynchronous and returns immediately, before its callback is invoked. You will need to find a way to instead return a promise that resovles when all of the callback's work is complete. (Consider that there are other HTTP client libraries that make it easier to get a promise instead of having to deal with callbacks.)

Expand my image upload from 1 to 5 photos; map/foreach?

I am creating an app in which you can upload a photo, with some other data, to Firebase. The uploading part worked perfect with one picture. However I have now added a multiple-image picture (select 1 to 5 pictures) and would like my image upload function to upload the 5 pictures in stead of the 1.
The image upload works with 1 image provided, so how can I rearrange my code to upload the x-amount of photos in the array?
The pictures are added in the photos array with the following data (output shown below is a console.log from the images fetched);
Array [
Object {
"exists": true,
"file": "ph://8905951D-1D94-483A-8864-BBFDC4FAD202/L0/001",
"isDirectory": false,
"md5": "f9ebcab5aa0706847235887c1a7e4740",
"modificationTime": 1574493667.505371,
"size": 104533,
"uri": "ph://8905951D-1D94-483A-8864-BBFDC4FAD202/L0/001",
},
With this didFocus I check if the fethedImages param is set and set the photos array to the fetched images (So all the data that is shown above)
const didFocusSubscription = props.navigation.addListener(
'didFocus', () => {
let fetchedImages = props.navigation.getParam('fetchedImages')
console.log(fetchedImages)
setPhotos(fetchedImages)
setImageValid(true)
calculateImageDimensions()
}
);
When I save the page and start dispatching the data I run the following command the uploadImage function is ran and returns an uploadurl, this is then saved later on in the dispatch function to the Firebase Database to be fetched later;
uploadurl = await uploadImageAsync(photos)
SO the uploadImageAsync starts with the photos array forwarded. How can I make sure the function below is started for every photo.uri in the array? Can I use .map of for each for this, and in what context should I be using this?
Also I am not quite sure how I can send back an array of URLs to be saved together with the rest of the information.
async function uploadImageAsync(photos) {
console.log('uploadImage is gestart')
// Why are we using XMLHttpRequest? See:
// https://github.com/expo/expo/issues/2402#issuecomment-443726662
const blob = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
resolve(xhr.response);
};
xhr.onerror = function (e) {
console.log(e);
reject(new TypeError('Network request failed'));
};
xhr.responseType = 'blob';
xhr.open('GET', photos, true);
xhr.send(null);
});
const ref = firebase
.storage()
.ref()
.child(uuid.v4());
const snapshot = await ref.put(blob);
// We're done with the blob, close and release it
blob.close();
return await snapshot.ref.getDownloadURL();
}
==============edited because of progress with uploading====================
Once again I am a little bit further. However the image upload function is now running, and because of is being multiple images I would like to await the response of all the images before continuing.
try {
uploadurl = await uploadImageAsync()
address = await getAddress(selectedLocation)
console.log(uploadurl)
if (!uploadurl.lenght) {
Alert.alert('Upload error', 'Something went wrong uploading the photo, plase try again', [
{ text: 'Okay' }
]);
return;
}
dispatch(
At this moment when I start the uploadImageAsync function. With he help of console.log I see it uploading the images, they also show up online. But while the pictures are uploading the upload url already returns with 0 and shows the Alert and stops the function.
uploadImageAsync = async () => {
const provider = firebase.database().ref(`providers/${uid}`);
let imagesArray = [];
try {
await photos.map(img => {
let file = img.data;
const path = "Img_" + uuid.v4();
const ref = firebase
.storage()
.ref(`/${uid}/${path}`);
ref.putString(file).then(() => {
ref
.getDownloadURL()
.then(images => {
imagesArray.push({
uri: images
});
console.log("Out-imgArray", imagesArray);
})
return imagesArray <== this return imagesArray is fired to early and starts the rest of my upload function.
} catch (e) {
console.error(e);
}
};
So a Discord chat pointed me in the way of a promise.all function for this to work. I tried that, but opened another stack overflow topic for getting this to work.
await response of image upload before continue function
The solution for my image upload function is in the topic above;
uploadImages = () => {
const provider = firebase.database().ref(`providers/${uid}`);
// CHANGED: removed 'let imagesArray = [];', no longer needed
return Promise.all(photos) // CHANGED: return the promise chain
.then(photoarray => {
console.log('all responses are resolved successfully');
// take each photo, upload it and then return it's download URL
return Promise.all(photoarray.map((photo) => { // CHANGED: used Promise.all(someArray.map(...)) idiom
let file = photo.data;
const path = "Img_" + uuid.v4();
const storageRef = firebase // CHANGED: renamed 'ref' to 'storageRef'
.storage()
.ref(`/${uid}/${path}`);
let metadata = {
contentType: 'image/jpeg',
};
// upload current photo and get it's download URL
return storageRef.putString(file, 'base64', metadata) // CHANGED: return the promise chain
.then(() => {
console.log(`${path} was uploaded successfully.`);
return storageRef.getDownloadURL() // CHANGED: return the promise chain
.then(fileUrl => ({uri: fileUrl}));
});
}));
})
.then((imagesArray) => { // These lines can
console.log("Out-imgArray: ", imagesArray) // safely be removed.
return imagesArray; // They are just
}) // for logging.
.catch((err) => {
console.error(err);
});
};

Categories

Resources