My example.downloadURL gives back an undefined - javascript

I am simply trying to test uploading images and I want to display the image, that is uploadoaded.
My code looks like this:
function uploadFile(files){
const storageRef = firebase.storage().ref(); //this references the firebase storage
const horseRef = storageRef.child("horse.jpg");
const file = files.item(0); //will return a list so lets take the first item
const task = horseRef.put(file); //to upload the file we call the put file
console.log(task);
task.then(snapshot => { //returns a buncha data including a snapshot url
const url = snapshot.downloadURL
document.getElementById("upload").setAttribute("src", url)
});
}
But the snapshot.downloadURL is giving back an undefined. Can you help me?

There isn't any downloadURL property on the snapshot which is an UploadTaskSnapshot. You need to use getDownloadURL() method on the storage reference to get the URL. Try refactoring the code as shown below:
task.then(async (snapshot) => {
const url = await snapshot.ref.getDownloadUrl()
document.getElementById("upload").setAttribute("src", url)
});

Related

How to Add Color to Static Mapbox Image Gotten from API

Below is the URL I pass to fetch API to get the image. It works great but the location pin is grey and I need it to be #800080 (purple). I get there's a marker-color parameter but not sure how to add it to the baseUrl string below. I've tried several different versions.
const baseUrl = `https://api.mapbox.com/styles/v1/mapbox/streets-v11/static/geojson(%7B%22type%22%3A%22Point%22%2C%22coordinates%22%3A%5B${geoLocation.longitude}%2C${geoLocation.latitude}%5D%7D)/${geoLocation.longitude},${geoLocation.latitude},15/500x300?access_token=${MAPBOX_API_KEY}`;
Relevant documentation which gives additional parameters but no clear examples: https://docs.mapbox.com/api/maps/static-images/#overlay-options
Code:
const getUrlExtension = (url) => {
return url.split(/[#?]/)[0].split('.').pop().trim();
};
const onImageEdit = async (imgUrl) => {
const imgExt = getUrlExtension(imgUrl);
const response = await fetch(imgUrl);
const blob = await response.blob();
const file = new File([blob], 'locationImage.' + imgExt, {
type: blob.type,
});
setImage(file);
setPreviewSrc(response.url);
};
function previewLocation(event) {
event.preventDefault();
const MAPBOX_API_KEY ='xyz';
// baseUrl based on https://docs.mapbox.com/api/maps/static-images/#overlay-options
const baseUrl = `https://api.mapbox.com/styles/v1/mapbox/streets-v11/static/geojson(%7B%22type%22%3A%22Point%22%2C%22coordinates%22%3A%5B${geoLocation.longitude}%2C${geoLocation.latitude}%5D%7D)/${geoLocation.longitude},${geoLocation.latitude},15/500x300?access_token=${MAPBOX_API_KEY}`;
onImageEdit(baseUrl);
}
Thanks in advance to anyone with Mapbox API experience!
I am unable to get the GeoJSON method to respond to the properties key too! Not sure what's going on there...
I am however able to get a pin showing in that color using the Marker method like the below.
https://api.mapbox.com/styles/v1/mapbox/streets-v11/static/pin-s-l+800080(-87.0186,32.4055)/-87.0186,32.4055,14/500x300?access_token=YOUR_TOKEN_HERE.

How to add data on nested array in Firestore with react-native

I would like to ask if is it possible to add data in a nested array.The result i want is this
But i get this when i add a new rating with the code i use
async function getAll(){
const userEmail= firebase.firestore().collection('users')
const snapshot=await userEmail.where('email','==',index.email).get()
if (snapshot.empty) {
console.log('No matching documents.');
return;
}
snapshot.forEach(doc => {
userEmail.doc(doc.id).set({userRatings2:firebase.firestore.FieldValue.arrayUnion({parking:[markerName]})},{merge:true})
userEmail.doc(doc.id).set({userRatings2:firebase.firestore.FieldValue.arrayUnion({rating:[currentRating]})},{merge:true})
console.log(userEmail.doc(doc.id));
});
}
getAll()
Unfortunately in Firebase Firestore you can't even change a simple Array value at a specific index. That means also that you can't save nested array values. You can read more about it on this answer.
The only way to do it is to download the whole Array make your modifications and save the whole array again to the databse. There is not much context of your app so I can't tell if that is a good solution for you. It depends how much data you have in the array.
I've managed to do it by using forEach function to an array of image path
const [imageUri, setImageUri] = useState([]);
const [uploading, setUploading] = useState(false);
const UploadImage = () => {
setUploading(true);
imageUri.forEach(async (image, index) => {
// setTransferred(0);
const pathToFile = image;
let filename = pathToFile.substring(pathToFile.lastIndexOf('-') + 1);
const extension = filename.split('.').pop();
const name = filename.split('.').slice(0, -1).join('.');
filename = name + Date.now() + '.' + extension;
const reference = storage().ref().child(`/userprofile/${filename}`);
// path to existing file on filesystem
// uploads file
const task = reference.putFile(pathToFile);
try {
await task;
const url = await reference.getDownloadURL();
downloadableURI.push(url);
if (index == imageUri.length - 1) {
setUploading(false);
Alert.alert(
'Image uploaded!',
'Your image has been uploaded to the Firebase Cloud Storage Successfully!',
);
}
} catch (e) {
console.log(e);
}
});
};
whenever the function is called, then the array of images is uploaded to firebase storage,

IPFS: base64-encoded image not showing as image

I have a simple function that tries to base64-encode an image and upload it to IPFS:
async function toIPFS() {
const node = await IPFS.create()
const data = fs.readFileSync('./src/assets/logo.png', 'base64').toString('base64')
const results = await node.add(data)
console.log(results.cid.string)
}
However, when I actually check the hash it displays as a long string:
iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyNpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHB...etc
How do I upload an image such that it actually displays as an image? What am I missing?
I've never worked with images so pardon if this is a noob question:)
What you're seeing returned is the file encoded as base64, if you want to store the image itself for later retrieval, this is how you'd do it:
async function toIPFS() {
const node = await IPFS.create()
const data = fs.readFileSync('./src/assets/logo.png')
const results = await node.add(data)
console.log(results.cid.string)
}

Can not get AEC model Data in Autodesk Forge

i try to activate Revit Levels and 2D Minimap extension in autodesk forge viewer, but can not get AEC Model Data. I got this worning`
i tried to get AEC data with this code
const url = window.location.search;
console.log(url);
const svf_path = `${url.replace("?", "/storage/").replace(/%20/g, " ")}`;
Autodesk.Viewing.endpoint.getItemApi = (endpoint, derivativeUrn, api) => {
return svf_path;
};
Autodesk.Viewing.Initializer(options, async () => {
const paths = svf_path.split("/");
const [dest, svf_dir] = [paths[2], paths[3]];
const url = `/api/viewer/dest/${dest}/svf/${svf_dir}/manifest`;
const response = await fetch(url);
const manifest = await response.json();
const init_div = document.getElementById("init_div");
viewer = new Autodesk.Viewing.GuiViewer3D(init_div, config3d);
const viewerDocument = new Autodesk.Viewing.Document(manifest);
const viewable = viewerDocument.getRoot().getDefaultGeometry();
viewer.start();
await viewerDocument.downloadAecModelData();
viewer.loadDocumentNode(viewerDocument, viewable)
.then(function (result) {
Autodesk.Viewing.Document.getAecModelData(viewable);
})
});
wats wrong in my code?
The warning comes from the BubbleNode.prototype.getAecModelData method. You are not calling it in your code but it's possible that it's being called by the LevelsExtension itself. Try configuring the extension so that it doesn't detect the AEC data automatically by passing in { autoDetectAecModelData: false } as the extension options.
Btw. to debug the issue on your side, you can also try getting the non-minified version of viewer3D.js, put a breakpoint to where the warning is being logged, and see the call stack when the breakpoint is hit.

How to upload an array of images to firebase storage?

Rightnow i'm using a array.map method to upload each file and gets the url in response but the thing is it gives me "C:\fakepath\pic1" in some files which creates a messs although it uploads it correctly(means i've seen the images in my firebase storage) but not get back the url in response
This is the code i'm using to put files
uploadPicsArr.map(function (pic, index) {
var storageRef = fbStorage.ref('images/'+token+'/'+pic.name);
// Upload file to Firebase Storage
var uploadTask = storageRef.put(pic.file);
uploadTask.on('state_changed', null, null, function () {
var downloadUrl = uploadTask.snapshot.downloadURL;
userInfo[pic.name] = downloadUrl;
})
if (uploadPicsArr.length == index + 1) {
fbDatabase.ref('users').push(userInfo).then(function (success){
browserHistory.push('/home');
});
}
})
fbStorage: firebase.storage()
uploadPicsArr = an array of objects and every object has a property name and file
name: name of the selected file
file: selected file
Please tell me what i'm doing wrong or if there's any other better way to upload the whole array and get each file URL in response then it would be better
I think you forget to pass the snapshot as a parameter in the complete function:
uploadPicsArr.map(function (pic, index) {
var storageRef = fbStorage.ref('images/'+token+'/'+pic.name);
// Upload file to Firebase Storage
var uploadTask = storageRef.put(pic.file);
uploadTask.on('state_changed', null, null, function (snapshot) {
userInfo[pic.name] = snapshot.downloadURL;
})
if (uploadPicsArr.length == index + 1) {
fbDatabase.ref('users').push(userInfo).then(function (success){
browserHistory.push('/home');
});
}
})

Categories