Linking firebase accounts, JSON and images together - javascript

I have uploaded my image to the firebase database easily enough using this code:
uploadImageButton.addEventListener('change', function(e){
var file = e.target.files[0];
var storageRef = storage.ref('pictures/' + file.name)
var task = storageRef.put(file);
})
I was wondering how to link this to a particular user I have stored in my JSON, or to a user I have in my accounts?
When I sign up a user I want to be able to store an image and there auth account and retrieve them whenever I wish.
So far I can retrieve the relevant JSON, but not the auth account or images.

For that you just create a folder with the user UID and place the file inside that folder.
uploadImageButton.addEventListener('change', function(e){
var file = e.target.files[0];
var storageRef = storage.ref('pictures/' + UID +'/' + file.name)
var task = storageRef.put(file);
})
Here UID is the userid corresponding to the account.
use the folowing code to get the download url:
task.on('state_changed', function(snapshot){
var url = uploadTask.snapshot.downloadURL;
var updates = {};
updates['users/'+ UID +'/profile_image'] = url;
firebase.database().ref().update(updates);
}
Now you are setting the download url in profile_image property.

Related

download pdf from URL into gDrive

I need to download a PDF from a link in the following format
fileURL = "https://docs.google.com/feeds/download/documents/export/Export?id=<...DOCID...>&revision=3970&exportFormat=pdf"
and add it to gDrive folder.
I have this code, but the generated file just contain "Blob" rather than the actual content
function dFile(fileName,fileURL) {
var response = UrlFetchApp.fetch(fileURL);
var fileBlob = response.getBlob().getAs('application/pdf');
var folder = DriveApp.getFolderById('..folderID..');
var result = folder.createFile(fileName,fileBlob,MimeType.PDF);
Logger.log("file created");
}
How to I download the actual PDF?
Update:
I have updated my code and now I get this as generated PDF. Which makes me think I need to auth, but not sure how to do it, I set up all auth in manifest already
function dFile(fileName,fileURL) {
var response = UrlFetchApp.fetch(fileURL);
var fileBlob = response.getBlob().getAs('application/pdf');
var folder = DriveApp.getFolderById('..folderID..');
var result = folder.createFile(fileBlob).setName(fileName);
Logger.log("file created");
}
In your script, how about the following modification?
From:
var response = UrlFetchApp.fetch(fileURL);
var fileBlob = response.getBlob().getAs('application/pdf');
To:
var response = UrlFetchApp.fetch(fileURL, { headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() } });
var fileBlob = response.getBlob();
I thought that in your endpoint, getBlob() returns the PDF format.
In your script, createFile is used. By this, the required scope has already been included. But, if an error is related to Drive API, please enable Drive API at Advanced Google services.
Note:
In your endpoint, if revision=3970 is not existing, an error occurs. Please be careful about this.
Reference:
getOAuthToken()

How to get file name from download link in firebase storage(Javascript, React)?

I've being trying to get files name from Firebase storage.
Right now I got a download link and trying to get name from it.
const showPhoto = () => {
var eventDOM = event.target;
var src = eventDOM.getAttribute('src');
setpickImage(src);
console.log(src);
// src = "https://firebasestorage.googleapis.com/v0/b....."
}
I need file name to delete file from storage.
If you want to map a download URL back to a file name, use the refFromURL method.
Also see the documentation on creating a reference from a download URL, which contains this example:
var httpsReference = storage.refFromURL('https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg');
From that Reference you can then get other properties like the file's name.
let fileName = httpsReference.name;
To get the file name and url or download link of the videos or files from the firebase storage you can use these two functions in javascript and react
// function to fetch videos / files from firebase storage
const fetchVideos = async() => {
const storageRef = firebase.storage().ref("your storage folder name");
const videos = [];
await storageRef
.listAll()
.then(async function(result) {
result.items.forEach(async function(videoRef) {
// getting the name of the file
const videoName = videoRef.name;
// getting the url of the file -> calling another function for this
const videoUrl = await getVideoUrl(videoRef);
// creating the object with name and url
const videoObj = {
videoName,
videoUrl,
};
console.log("video obj", videoObj);
videos.push(videoObj);
});
})
.catch(function(error) {
// Handle any errors
return [];
});
}
// function to get download url
const getVideoUrl = (imageRef) => {
const videoLink = imageRef
.getDownloadURL()
.then(function(videoUrl) {
console.log("videoUrl", videoUrl);
return videoUrl;
})
.catch(function(error) {
// Handle any errors
return "";
});
return videoLink;
};

Get Download Url after firebase's resize extension completed

This is what I am trying to achieve, implement the firebase's resize image extension, upload an image, then when the resize is completed, add that dowloadUrl's thumbs to a Cloud Firestore document. This question helps me, but still can not identify the thumbs and get the download URL, this is what am have been trying so far.
Note: I set my thumbnail to be at root/thumbs
const functions = require('firebase-functions');
const { Storage } = require('#google-cloud/storage');
const storage = new Storage();
exports.thumbsUrl = functions.storage.object().onFinalize(async object => {
const fileBucket = object.bucket;
const filePath = object.name;
const contentType = object.contentType;
if (fileBucket && filePath && contentType) {
console.log('Complete data');
if (!contentType.startsWith('thumbs/')) {
console.log('This is not a thumbnails');
return true;
}
console.log('This is a thumbnails');
} else {
console.log('Incomplete data');
return null;
}
});
Method 1 : Client Side
Don't change the access token when creating the thumbnail.
Edit the function from gcloud cloud function console
Go to the function code by clicking detailed usage stats
Then click on code
Edit the following lines
Redeploy the function again
// If the original image has a download token, add a
// new token to the image being resized #323
if (metadata.metadata.firebaseStorageDownloadTokens) {
// metadata.metadata.firebaseStorageDownloadTokens = uuidv4_1.uuid();
}
Fetch the uploaded image using getDownloadURLfunction
https://firebasestorage.googleapis.com/v0/b/<project_id>/o/<FolderName>%2F<Filename>.jpg?alt=media&token=xxxxxx-xxx-xxx-xxx-xxxxxxxxxxxxx
Because the access token will be similar
https://firebasestorage.googleapis.com/v0/b/<project_id>/o/<FolderName>%2Fthumbnails%2F<Filename>_300x300.jpg?alt=media&token=xxxxxx-xxx-xxx-xxx-xxxxxxxxxxxxx
Method 2: Server Side
Call this function after thumbnail is created
var storage = firebase.storage();
var pathReference = storage.ref('users/' + userId + '/avatar.jpg');
pathReference.getDownloadURL().then(function (url) {
$("#large-avatar").attr('src', url);
}).catch(function (error) {
// Handle any errors
});
you need to use filePath for checking the thumbs
if(filePath.startswith('thumbs/'){...}
contentType has the metadata of files like type of image and etc.
FilePath will have the full path.

How can I store download URL of file uploaded to Firebase database

I want to store the download URL of an image as part of the post data, but am not able to do so, as the downloadURL is not stored in the imgURL variable.
However, the downloadURL is able to print properly with console.log.
var postKey = firebase.database().ref('Posts/').push().key;
var imgURL = null;
uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
imgURL = downloadURL;
console.log('File available at', downloadURL);
});
var updates = {};
var postData = {
url: imgURL,
caption: $("#imageCaption").val()
};
updates['/Posts/' + postKey] = postData;
firebase.database().ref().update(updates);

Retrieving current user data from firebase

I'm able to retrieve the data but it's only showing the data of the last user in the database. The users are listed by their uid. Below are the code and screenshot of the data from firebase. Help me out, guys!
var database = firebase.database().ref('users');
database.on("child_added", function(snapshot) {
var snapVal = snapshot.val();
displayName.innerHTML = snapVal.mUsername;
console.log(snapVal);
var badge = document.createElement('span');
badge.textContent = 'view details';
badge.setAttribute('class','badge');
var list = document.createElement('a');
list.textContent = snapVal.mUsername;
list.setAttribute('href', '#');
list.setAttribute('class', 'list-group-item');
patientList.appendChild(list);
list.appendChild(badge);
var userIcon = document.createElement('i');
userIcon.setAttribute('class','far fa-user');
list.insertBefore(userIcon, list.childNodes[0])
},
function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
You should refer to the specific user's node to retrieve the information.
Your code should look like:
var userRef = firebase.database().ref(`users/${user_node_key}`); // user_node_key should be the node containing the user info.
You should be able to get the node key using the current user's object.
and then call once on the userRef if you just need to get the detail once or on if you need to listen all the changes on that user.
The code should look like:
userRef.once('value').then(function(snapshot) {
//use snapshot to get the users data
});

Categories

Resources