how to store a uploaded image to two different path/places in firebase Storage? I tried this but it isn't working
const { currentUser } = firebase.auth();
const ref = firebase.storage().ref().child(`images/${currentUser.uid}`);
const ref = firebase.storage().ref().child('photos')
const snapshot = await ref.put(blob);
blob.close();
Okay so first, you can't re-declare variables like that (const ref = ...; then const ref = ....; right below it). Second, you need to perform put on each ref. So should look something like this:
const { currentUser } = firebase.auth();
const ref1 = firebase.storage().ref().child(`images/${currentUser.uid}`);
const ref2 = firebase.storage().ref().child('photos')
const snapshot1 = await ref1.put(blob);
const snapshot2 = await ref2.put(blob);
blob.close();
Or if you want to have a little more optimized code:
const { currentUser } = firebase.auth();
const ref = firebase.storage().ref();
const imagesUpload = await ref.child(`images/${currentUser.uid}`).put(blob);
const photosUpload = await ref.child('photos').put(blob);
blob.close();
If you want to be more advanced with this and have only a single upload task, read more here: https://cloud.google.com/storage/docs/json_api/v1/how-tos/batch
Related
I am using web3js to get transaction details
my code:
const transactionHash = this._req.query.transactionHash;
const transaction = await this._web3.eth.getTransactionReceipt(transactionHash);
const logs = await transaction.logs;
const log = await logs.find(i => i.transactionHash === transactionHash);
const topics = await log.topics;
const test = await this._web3.eth.abi.decodeParameter('bytes32', topics[0]);
const from = await this._web3.eth.abi.decodeParameter('address', topics[1]);
const to = await this._web3.eth.abi.decodeParameter('address', topics[2]);
const value = await this._web3.eth.abi.decodeParameter('uint256', log.data);
const amount = await this._web3.utils.fromWei(value);
But I still haven't got the token name of the transaction
Give me some suggestions, thanks
To get the token symbol, you need to call the token contract's function symbol().
Since the Transfer event was emitted by the token contract, you have its address in the log.address property. Then you just need to call the symbol() function:
const abiJson = [
{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"}
];
const contract = new web3.eth.Contract(abiJson, log.address);
const symbol = await contract.methods.symbol().call();
I saved data on workbook on following code
export const storeSettingsToWorkbook = async (settingsType: Settings, storeData:
WorkbookModel) => {
return Excel.run(async (context) => {
const originalXml = createXmlObject(storeData);
const customXmlPart = context.workbook.customXmlParts.add(originalXml);
customXmlPart.load("id");
await context.sync();
// Store the XML part's ID in a setting
const settings = context.workbook.settings;
settings.add(settingsTitles[settingsType], customXmlPart.id);
await context.sync();
})
}
when i get data -it works normally.But when i want to get this data form another "add-in" on Excel- I cannot get this data
const {settings} = context.workbook;
const sheet = context.workbook.worksheets.getActiveWorksheet().load("items");
const xmlPartIDSetting = settings.getItemOrNullObject(settingsTitles[settingsType]).load("value");
await context.sync();
if (xmlPartIDSetting.value) {
const customXmlPart = context.workbook.customXmlParts.getItem(xmlPartIDSetting.value);
const xmlBlob = customXmlPart.getXml();
await context.sync()
const parsedObject = parseFromXmlString(xmlBlob.value);
const normalizedData = normalizeParsedData(parsedObject);
Any ideas?
Thanks for reaching us.
This is by design. Each addin has its own setting and cannot share with each other.
You can use 'context.workbook.properties.custom' as a workaround.
You can also use 'context.workbook.worksheets.getActiveWorksheet().customProperties', but the two add-ins are required to be on the same worksheet.
In my cloud functions, I'm trying to delete an image based on its url, but I think that I don't use correctly the API as I'm getting errors :
const admin = require('firebase-admin');
exports.deleteImageWhenOfferDeleted = functions.firestore
.document('offers/{offerId}')
.onDelete(async(snap, context) => {
console.log('----------------start function--------------------')
const deletedOffer = snap.data();
var imageUrlToDelete = deletedOffer.imageUrl;
await admin.storage.getPathStorageFromUrl(imageUrlToDelete).delete();
function getPathStorageFromUrl(url){
const baseUrl = "https://firebasestorage.googleapis.com/v0/b/muslim-coloc.appspot.com/o/";
let imagePath = url.replace(baseUrl,"");
const indexOfEndPath = imagePath.indexOf("?");
imagePath = imagePath.substring(0,indexOfEndPath);
imagePath = imagePath.replace("%2F","/");
return imagePath;
}
I think you're missing brackets after storage word.
You need to get an instance of storage object.
admin.storage.getReferenceFromUrl(...)
should be
admin.storage().getReferenceFromUrl(...)
BTW: Consider using TypeScript, because it catches errors like that during compilation.
var db = firebase.firestore();
db.settings({ timestampsInSnapshots: true });
const newgame = document.querySelector('addingnewgame');
function addnewgame(doc){
let gamebase = document.createElement('a');
let gamelink = gamebase.href;
let gamename = gamebase.innerHTML;
let gameimage = document.createElement('img');
gameimage = doc.data().gameimglink;
gamename.innerText = doc.data().gamename;
gamebase.setAttribute('data-id', doc.id);
gamebase.setAttribute("src" , gameimage);
gamebase.setAttribute("href" , gamelink);
gamebase.setAttribute("innerhtml", gamename);
gamelink.innerText = doc.data().gameurl;
newgame.appendChild(gamebase);
}
db.collection('New Game').get().then((snapshot) => {
snapshot.docs.forEach(doc =>
{
addnewgame(doc);
})
})
there are few errors kindly please help me out. i am working on a project based on cloud firebase ,help me out to resolve it
I think you want to have a link around an image.
Working example:
let gamebase = document.createElement('a');
let gameimage = document.createElement('img');
gamebase.href = 'https://stackoverflow.com/help/how-to-ask';
gamebase.setAttribute('data-id', 'some_id_from_doc');
gameimage.src = 'https://cdn.sstatic.net/Sites/stackoverflow/Img/favicon.ico?v=ec617d715196';
gameimage.title = 'How do I ask a good question?';
gamebase.appendChild(gameimage);
document.querySelector('#container').appendChild(gamebase);
<div id="container"></div>
I use one Cloud Function to resize images and the second on for uploading a new image URL to Cloud Firestore.
But something doesn't work, because the second function never runs.
I need the uid and postId where I can update the url.
How can I call the second function to update the img url in Firestore?
Code
const { functions, tmpdir, dirname, join, sharp, fse, gcs } = require('../../admin');
const runtimeOpts = {
timeoutSeconds: 120,
memory: '1GB',
};
exports.resizeImages = functions
.runWith(runtimeOpts)
.storage.object()
.onFinalize(async (object, context) => {
const bucket = gcs.bucket(object.bucket);
const filePath = object.name;
const fileName = filePath.split('/').pop();
const bucketDir = dirname(filePath);
const workingDir = join(tmpdir(), 'resize');
const tmpFilePath = join(workingDir, 'source.png');
if (fileName.includes('#s_') || !object.contentType.includes('image')) {
return false;
}
await fse.ensureDir(workingDir);
await bucket.file(filePath).download({ destination: tmpFilePath });
// creates 3 new images with these sizes..
const sizes = [1920, 720, 100];
var newUrl = null;
const uploadPromises = sizes.map(async size => {
const ext = fileName.split('.').pop();
const imgName = fileName.replace(`.${ext}`, '');
const newImgName = `${imgName}#s_${size}.${ext}`;
var imgPath = join(workingDir, newImgName);
newUrl = imgPath;
await sharp(tmpFilePath)
.resize({ width: size })
.toFile(imgPath);
return bucket.upload(imgPath, {
destination: join(bucketDir, newImgName),
});
});
await Promise.all(uploadPromises);
//second function
functions.firestore.document('users/{uid}/posts/{id}').onCreate(async (snap, context) => {
console.log(context.params);
const uid = context.params.uid;
const userPost = functions.firestore.doc('users/{uid}/posts}');
userPost.update({
url: newUrl,
});
});
return fse.remove(workingDir);
});
Your second function appears to be embedded in the first. This isn't going to work. All function definition must be at the top level so they can be detected by the Firebase CLI and deployed separately.
If you don't actually want two separate function definitions, just perform all the work in one function, and don't try to use the functions SDK to do any of that work. The Functions SDK is just for defining the functions for deployment.