Firebase Cloud Function connection error when bucket.upload() - firebase

When I try to upload the generated PDF file to storage bucket, the firebase logs gives me that response after log "Init upload of file...":
Function execution took 3721 ms, finished with status: 'connection
error'
Maybe the problem can be the order of Promises. But I'm beginner with Cloud Functions and Node.js to reorder that.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const pdf = require('html-pdf');
const gcs = require('#google-cloud/storage')({keyFilename: './service_account.json'});
const handlebars = require('handlebars');
const path = require('path');
const os = require('os');
const fs = require('fs');
const bucket = gcs.bucket(bucketURL);
admin.initializeApp(functions.config().firebase);
var html = null;
exports.generatePdf = functions.https.onRequest((request, response) => {
// data to apply to template file
const user = {
"date": new Date().toISOString(),
"title": "Voucher",
"body": "Voucher body"
};
const options = {
"format": 'A4',
"orientation": "portrait"
};
const localPDFFile = path.join(os.tmpdir(), 'localPDFFile.pdf');
try {
const source = fs.readFileSync(__dirname + '/voucher.html', 'utf8');
html = handlebars.compile(source)(user);
} catch (error) {
console.error(error);
}
const phantomJsCloud = require("phantomjscloud");
const browser = new phantomJsCloud.BrowserApi(phantomApiKey);
var pageRequest = { content: html, renderType: "pdf" };
// // Send our HTML to PhantomJS to convert to PDF
return browser.requestSingle(pageRequest)
.then(function (userResponse) {
if (userResponse.statusCode !== 200) {
console.log("invalid status code" + userResponse.statusCode);
} else {
console.log('Successfully generated PDF');
// Save the PDF locally
fs.writeFile(localPDFFile, userResponse.content.data, {
encoding: userResponse.content.encoding,
}, function (err) {
console.log('Init upload of file...' + localPDFFile);
// Upload the file to our cloud bucket
return bucket.upload(localPDFFile, {
destination: '/pdfs/voucher.pdf',
metadata: {
contentType: 'application/pdf'
}
}).then(() => {
console.log('bucket upload complete: ' + localPDFFile);
response.status(200).send({
message: 'PDF Gerado com sucesso!',
address: localPDFFile
});
return true;
}).catch(error => {
response.status(400).send({
message: 'Error on bucket upload!',
error: error
});
return false;
});
});
return true;
}
return true;
});
})

Related

Next Js File Attachments in Contact Forms

I'm trying to upload a file to my server to send in the contact form and then have the file delete itself once sent. I've made a start with my code by using multer and I've followed a few guides that were using express to handle the api but I want to use the Next js api provided. I just can not seem to get this file to upload.
I've commented out the nodemailer call so it doesn't send an email every time I test it but, here is my current code.
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import nodemailer from "nodemailer";
import multer from "multer";
export default async function handler(req, res) {
let Storage = multer.diskStorage({
destination: (req, file, callback) => {
callback(null, "../../files");
},
filename: (req, file, callback) => {
console.log(file);
callback(
null,
file.fieldname + "_" + Date.now() + "_" + file.originalname
);
},
});
let upload = multer({
storage: Storage,
}).single("careerCV");
upload(req, res, function (err) {
if (err) {
console.log(err);
return res.end("something went wrong");
} else {
var {
careerName,
careerEmail,
careerMessage,
careerTelephone,
careerBadge,
careerCV,
} = req.body;
console.log(careerName);
console.log(careerEmail);
console.log(careerMessage);
console.log(careerTelephone);
console.log(careerBadge);
console.log(careerCV);
}
});
// const {
// careerName,
// careerEmail,
// careerMessage,
// careerTelephone,
// careerBadge,
// careerCV,
// } = req.body;
// const transporter = nodemailer.createTransport({
// host: "smtp.gmail.com",
// port: 465,
// secure: true,
// auth: {
// user: process.env.user,
// pass: process.env.pass,
// },
// });
// try {
// const emailRes = await transporter.sendMail({
// from: `${careerName} <${careerEmail}>`,
// replyTo: `${careerName} <${careerEmail}>`,
// to: "deanparkim1987#gmail.com",
// subject: `Career Form Submission from ${careerName}`,
// html: `<p>You have a new Career form submission</p><br>
// <p><strong>Name: </strong> ${careerName}</p><br>
// <p><strong>Email: </strong> ${careerEmail}</p><br>
// <p><strong>Phone Number: </strong> ${careerTelephone}</p><br>
// <p><strong>Badge Number: </strong> ${careerBadge}</p><br>
// <p><strong>Message: </strong> ${careerMessage}</p>`,
// attachments: careerCV,
// });
// console.log("Message sent: %s", emailRes.messageId);
// } catch (error) {
// console.error(error);
// }
console.log(req.body);
res.status(200).json(req.body);
}

Next.js user get location

I want to bring the user location with cloudflare. Localhost and google cloud bring different results. I want to access the location information of the member, not the server. What can I use instead of getStaticProps?
My Code;
export async function getStaticProps() {
const one = await fetch("https://www.cloudflare.com/cdn-cgi/trace");
const two = await one.text();
var data = two.replace(/[\r\n]+/g, '","').replace(/\=+/g, '":"');
data = '{"' + data.slice(0, data.lastIndexOf('","')) + '"}';
var locale = JSON.parse(data);
return {
props: { locale },
};
}
function myPage(props) {
return (props.locale.loc)
}
solved code;
let [locData, setLocData] = useState("EN");
useEffect(() => {
fetch("https://www.cloudflare.com/cdn-cgi/trace")
.then((response) => response.text())
.then((two) => {
var data = two.replace(/[\r\n]+/g, '","').replace(/\=+/g, '":"');
data = '{"' + data.slice(0, data.lastIndexOf('","')) + '"}';
var locale = JSON.parse(data);
setLocData(locale.loc);
});
}, []);

NzUploadModule with AngularFireStorage

I'm trying to upload a file with AngularFireStorage service. File is uploaded and I can get download URL, but I can't pass status(progress,downloadurl) to nz-upload component. Is there someone solves it? I think S3 way may look like similar.
uploadFile = (item: UploadXHRArgs) => {
console.log('call uploadFile');
console.log(item);
const file = item.file;
const filePath = `${this.authService.user.uid}/${file.uid}`;
const fileRef = this.storage.ref(filePath);
const task = this.storage.upload(filePath, file)
return task.snapshotChanges().pipe(
finalize(() => {
fileRef.getDownloadURL().subscribe(result => {
console.log(result);
});
})
)
.subscribe();
}
handleChange({ file, fileList }: UploadChangeParam): void {
console.log(file.status);
const status = file.status;
if (status !== 'uploading') {
console.log(file, fileList);
}
if (status === 'done') {
this.msg.success(`${file.name} file uploaded successfully.`);
} else if (status === 'error') {
this.msg.error(`${file.name} file upload failed.`);
}
}
In browser console
call uploadFile
Object { action: "", name: "file", headers: undefined, file: File, postFile: File, data: undefined, withCredentials: false, onProgress: onProgress(e), onSuccess: onSuccess(ret, xhr), onError: onError(xhr)
}
uploading
https://firebasestorage.googleapis.com/v0/b/xxxx.appspot.com/o/bc7Q7zMxCWdJW0FtHrWtC0y6Vle2%2Fmnjvjqua0z?alt=media&token=6a50e16d-2b42-43b3-907a-add7f7a9b8f6
On a page
Solved, thanks to https://github.com/ezhuo/ngx-alain/blob/master/src/app/#core/utils/image.compress.service.ts#L123
uploadFile = (item: UploadXHRArgs) => {
const file = item.file;
const filePath = `${this.authService.user.uid}/${file.uid}`;
const fileRef = this.storage.ref(filePath);
const task = this.storage.upload(filePath, file);
return task.snapshotChanges().pipe(
finalize(() => {
fileRef.getDownloadURL().subscribe(result => {
item.onSuccess(result, item.file, result);
});
})
)
.subscribe(
(result) => {
const event = { percent: 0};
event.percent = (result.bytesTransferred / result.totalBytes) * 100;
item.onProgress(event, item.file);
},
err => {
item.onError(err, item.file);
}
);
}
P.S. Still trying to understand item.onSuccess(result, item.file, result); but upload and preview and progress, works.

Do I need to run firebase command in my project directory in order to install firebase cloud function?

Lately I have been facing problem about install firebase cloud function for my Ionic project, I want to ask that should we run firebase init and firebase deploy only in the project directory in order to install firebase cloud function?
For example,my project directory is C:/users/name/project
but I am unable to run any firebase command in the directory because an error message will appear 'firebase' is not recognized as an internal or external command,operable program or batch file. and I am only able to run firebase command in C:/program files/git/usr/local directory, is this a reason why I am unable to install the firebase cloud function successfully?
-
-
To be more clear to my question, this is the dependencies inside the file tools/functions/package.json
"name": "functions",
"description": "Cloud Functions for Firebase",
"dependencies": {
"#google-cloud/storage": "^0.4.0",
"child-process-promise": "^2.2.0",
"firebase": "^7.5.0",
"firebase-admin": "^5.11.0",
"firebase-functions": "^3.3.0",
"mkdirp": "^0.5.1",
"mkdirp-promise": "^4.0.0"
},
"private": true
}
This is my ionic info
Ionic CLI : 5.4.6 (c:\Users\CJ\AppData\Roaming\npm\node_modules\ionic)
Ionic Framework : ionic-angular 3.9.5
#ionic/app-scripts : 3.2.2
Cordova:
Cordova CLI : not installed
Cordova Platforms : none
Cordova Plugins : no whitelisted plugins (0 plugins total)
Utility:
cordova-res : not installed
native-run : not installed
System:
Android SDK Tools : 26.1.1 (C:\Users\CJ\AppData\Local\Android\Sdk)
NodeJS : v12.13.0 (C:\Program Files\nodejs\node.exe)
npm : 6.13.4
OS : Windows 10
This is the code of index.js
'use strict';
const functions = require('firebase-functions');
const mkdirp = require('mkdirp-promise');
// Include a Service Account Key to use a Signed URL
const gcs = require('#google-cloud/storage')({keyFilename: 'service-account-credentials.json'});
const admin = require('firebase-admin');
admin.initializeApp();
const spawn = require('child-process-promise').spawn;
const path = require('path');
const os = require('os');
const fs = require('fs');
// Thumbnail size
const THUMB_MAX_HEIGHT = 256; // Max height and width of the thumbnail in pixels.
const THUMB_MAX_WIDTH = 512;
const THUMB_PREFIX = 'thumb_'; // Thumbnail prefix added to file names.
// Order status
const STATUS_PENDING = 'pending';
const STATUS_COMPLETE = 'complete';
/**
* When an image is uploaded in the Storage bucket We generate a thumbnail automatically using
* ImageMagick.
* After the thumbnail has been generated and uploaded to Cloud Storage,
* we write the public URL to the Firebase Realtime Database.
*/
exports.generateThumbnail = functions.storage.object().onFinalize((object, context) => {
// File and directory paths.
const filePath = object.name;
const contentType = object.contentType; // This is the image Mimme type
const fileDir = path.dirname(filePath);
const fileName = path.basename(filePath);
const thumbFilePath = path.normalize(path.join(fileDir, `${THUMB_PREFIX}${fileName}`));
const tempLocalFile = path.join(os.tmpdir(), filePath);
const tempLocalDir = path.dirname(tempLocalFile);
const tempLocalThumbFile = path.join(os.tmpdir(), thumbFilePath);
// Exit if this is triggered on a file that is not an image.
if (!contentType.startsWith('image/')) {
console.log('This is not an image.');
return null;
}
// Exit if the image is already a thumbnail.
if (fileName.startsWith(THUMB_PREFIX)) {
console.log('Already a Thumbnail.');
return null;
}
// Cloud Storage files.
const bucket = gcs.bucket(object.bucket);
const file = bucket.file(filePath);
const thumbFile = bucket.file(thumbFilePath);
const metadata = {contentType: contentType};
// Create the temp directory where the storage file will be downloaded.
return mkdirp(tempLocalDir).then(() => {
// Download file from bucket.
return file.download({destination: tempLocalFile});
}).then(() => {
console.log('The file has been downloaded to', tempLocalFile);
// Generate a thumbnail using ImageMagick.
return spawn('convert', [
tempLocalFile,
'-thumbnail',
`${THUMB_MAX_WIDTH}x${THUMB_MAX_HEIGHT}^`,
'-gravity',
'center',
'-crop',
`${THUMB_MAX_WIDTH}x${THUMB_MAX_HEIGHT}+0+0`,
tempLocalThumbFile
], {capture: ['stdout', 'stderr']}
);
}).then(() => {
console.log('Thumbnail created at', tempLocalThumbFile);
// Uploading the Thumbnail.
return bucket.upload(tempLocalThumbFile, {destination: thumbFilePath, metadata: metadata});
}).then(() => {
console.log('Thumbnail uploaded to Storage at', thumbFilePath);
// Once the image has been uploaded delete the local files to free up disk space.
fs.unlinkSync(tempLocalFile);
fs.unlinkSync(tempLocalThumbFile);
// Get the Signed URLs for the thumbnail and original image.
const config = {
action: 'read',
expires: '03-01-2500'
};
return Promise.all([
thumbFile.getSignedUrl(config),
file.getSignedUrl(config)
]);
}).then(results => {
console.log('Got Signed URLs.');
const thumbResult = results[0];
const originalResult = results[1];
const thumbFileUrl = thumbResult[0];
const fileUrl = originalResult[0];
// Add the URLs to the Database
return admin.database().ref('images').push({path: fileUrl, thumbnail: thumbFileUrl});
}).then(() => console.log('Thumbnail URLs saved to database.'));
});
// listen for new order created then calculate order value
exports.calOrder = functions.firestore.document('orders/{orderId}').onCreate(function (snap, context) {
// Grab the current value of what was written to the Realtime Database
const original = snap.data();
// log record detail
console.log('Received order', context.params.orderId);
console.log('Order data', original);
// set status to pending
snap.ref.set({status: STATUS_PENDING}, {merge: true});
// set order number
var orderSettingDocRef = admin.firestore().collection('settings').doc('order');
orderSettingDocRef.get().then(doc => {
let val = 2018000001;
if (doc.exists) {
val = doc.data().orderNumber + 1;
orderSettingDocRef.update({orderNumber: val});
} else {
orderSettingDocRef.set({orderNumber: val});
}
snap.ref.set({orderNumber: val}, {merge: true});
});
// set createdAt & updatedAt
snap.ref.set({
createdAt: Date.now(),
updatedAt: Date.now(),
}, {merge: true});
// calculate order data
let total = 0;
let itemDocRef;
let soldCount = 0;
original.items.map(item => {
total += item.subTotal;
// update item report
itemDocRef = admin.firestore().collection('items').doc(item.id);
itemDocRef.get().then(function (snapshot) {
if (snapshot.exists) {
soldCount = snapshot.data().soldCount ? snapshot.data().soldCount + item.quantity : item.quantity;
itemDocRef.update({soldCount: soldCount});
}
});
});
// send notifications to store
admin.firestore().collection('notifications').doc(original.store.id).collection('orders').add({
orderId: context.params.orderId
});
// write total to firebase
// should convert total to float
return snap.ref.set({total: total.toFixed(2) / 1}, {merge: true});
});
// listen to order update
exports.calReport = functions.firestore.document('orders/{orderId}').onUpdate(function (change, context) {
// Grab the current value of what was written to the Realtime Database
const newValue = change.after.data();
// Grab previous value for comparison
const previousValue = change.before.data();
// order total value
const orderTotal = parseFloat(newValue.total);
const date = new Date();
console.log('status', newValue.status, previousValue.status);
// send notification if order's status has changed
if (newValue.status !== previousValue.status) {
// notify to user if order has changed status
if (previousValue.status) {
admin.firestore().collection('notifications').doc(newValue.userId).collection('orders').add({
orderId: context.params.orderId
});
}
// build report data
const reportDocRef = admin.firestore().collection('reports').doc(newValue.store.id);
var reportData;
reportDocRef.get().then(function (doc) {
// set initial data
if (doc.exists) {
reportData = doc.data();
if (reportData.order) {
if (reportData.order[newValue.status]) {
reportData.order[newValue.status]++;
} else {
reportData.order[newValue.status] = 1;
}
if (reportData.order[previousValue.status] && (reportData.order[previousValue.status] > 1)) {
reportData.order[previousValue.status]--;
} else {
reportData.order[previousValue.status] = 0;
}
} else {
reportData.order = {};
reportData.order[newValue.status] = 1;
}
} else {
reportData = {order: {}, sale: {}};
reportData.order[newValue.status] = 1;
}
if (newValue.status == STATUS_COMPLETE) {
if (reportData.sale.total) {
reportData.sale.total += orderTotal;
} else {
reportData.sale.total = orderTotal;
}
const year = date.getFullYear();
if (reportData.sale[year]) {
reportData.sale[year].total += orderTotal;
} else {
reportData.sale[year] = {
total: orderTotal
};
}
const month = date.getMonth() + 1;
if (reportData.sale[year][month]) {
reportData.sale[year][month].total += orderTotal;
} else {
reportData.sale[year][month] = {
total: orderTotal
};
}
const today = date.getDate();
if (reportData.sale[year][month][today]) {
reportData.sale[year][month][today].total += orderTotal;
} else {
reportData.sale[year][month][today] = {
total: orderTotal
};
}
}
console.log('report', reportData);
return reportDocRef.set(reportData);
});
}
});
// listen to item created
exports.itemOnCreate = functions.firestore.document('items/{itemId}').onCreate(function (snap, context) {
// Grab the current value of what was written to the Realtime Database
const original = snap.data();
console.log('item created: ', original);
updateCatItemCount(original.categoryId);
return updateItemCount(original.storeId);
});
// listen to item deleted
exports.itemOnDelete = functions.firestore.document('items/{itemId}').onDelete(function (snap, context) {
// Grab the previous value of what was written to the Realtime Database
const original = snap.data();
updateCatItemCount(original.categoryId);
return updateItemCount(original.storeId);
});
// listen for item review then update item & store rating
exports.calRate = functions.firestore.document('items/{itemId}/reviews/{reviewId}').onCreate(function (snap, context) {
// Grab the current value of what was written to the Realtime Database
const original = snap.data();
var itemDocRef = admin.firestore().collection('items').doc(context.params.itemId);
// calculate avg rating for item
itemDocRef.get().then(function (doc) {
var item = doc.data();
var storeDocRef = admin.firestore().collection('stores').doc(item.storeId);
if (item.rateCount) {
item.rating = (item.rating * item.rateCount + original.rating) / (item.rateCount + 1);
item.rateCount++;
} else { // on first time
item.rating = original.rating;
item.rateCount = 1;
}
itemDocRef.update({
rating: item.rating.toFixed(2),
rateCount: item.rateCount
});
storeDocRef.get().then(function (storeDoc) {
var store = storeDoc.data();
if (store.rateCount) {
store.rating = (store.rating * store.rateCount + original.rating) / (store.rateCount + 1);
store.rateCount++;
} else { // on first time
store.rating = original.rating;
store.rateCount = 1;
}
storeDocRef.update({
rating: store.rating.toFixed(2),
rateCount: store.rateCount
});
});
});
return true;
});
// update store's itemCount
var updateItemCount = function (storeId) {
var itemCount = 0;
var storeDocRef = admin.firestore().collection('stores').doc(storeId);
return admin.firestore().collection('items').where('storeId', '==', storeId).get().then(function (docs) {
itemCount = docs.size;
return storeDocRef.update({itemCount: itemCount});
});
};
// update category item count
var updateCatItemCount = function (catId) {
var itemCount = 0;
var storeDocRef = admin.firestore().collection('categories').doc(catId);
return admin.firestore().collection('items').where('categoryId', '==', catId).get().then(function (docs) {
itemCount = docs.size;
return storeDocRef.update({itemCount: itemCount});
});
};

react-native-fetch-blob is blocking firebase calls n react native app

I have a react native app that uses Firebase, firestore.
for uploading images i am using "react-native-fetch-blob" to create a Blob.
in the js file that I use to upload the file, my code look like this:
const Blob = RNFetchBlob.polyfill.Blob
const fs = RNFetchBlob.fs
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
window.Blob = Blob
**
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
**
because of this window.XMLHttpRequest my app is blocked and not getting any response from firebase(not catch / nothing => just passing thrue the code).
if i removed this line i can read/write to the firestore, bat I can't upload an image.
is there anything i can do for uploading images and keep writing to firestore?
Heare is my page:
import ImagePicker from 'react-native-image-crop-picker';
import RNFetchBlob from 'react-native-fetch-blob'
import firebase from 'firebase';
const Blob = RNFetchBlob.polyfill.Blob
const fs = RNFetchBlob.fs
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
window.Blob = Blob
export const choozFile = (isSmalImg) => {
let options = {
width: isSmalImg ? 100 : 690,
height: isSmalImg ? 100 : 390,
cropping: true,
mediaType: 'photo'
};
return new Promise((resolve, reject) => {
ImagePicker.openPicker(options).then(response => {
let source = { uri: response.path };
resolve({ avatarSource: source, isProfileImg: isSmalImg })
})
});
}
export const addReportToFirebase = (obj = {}, uri, isProfile, mime = 'application/octet-stream') => {
obj["uId"] = "JtXNfy34BNRfCoRO6luwhIJke0l2";
const storage = firebase.storage();
const db = firebase.firestore();
const uploadUri = uri;
const sessionId = new Date().getTime();
let uploadBlob = null;
const imageRef = storage.ref(`images${isProfile ? '/profile' : ''}`).child(`${sessionId}`)
fs.readFile(uploadUri, 'base64')
.then((data) => {
return Blob.build(data, { type: `${mime};BASE64` })
})
.then((blob) => {
uploadBlob = blob
return imageRef.put(blob, { contentType: mime })
})
.then(() => {
uploadBlob.close()
imageRef.getDownloadURL().then((url)=>{
obj['image'] = url;
db.collection("reports").add(obj).then(() => {
console.log("Document successfully written!");
}).catch((err) => {
console.error("Error writing document: ", err);
});
})
})
.catch((error) => {
console.log('upload Image error: ', error)
})
};
I had same issue , i did some trick to resolve this. This might not be most correct solution but it worked for me.
Trick is keep RNFetchBlob.polyfill.XMLHttpRequest in window.XMLHttpRequest only for the upload operation. Once you done with uploading image to storage revert window.XMLHttpRequest to original value.
your code will look like this.
import ImagePicker from 'react-native-image-crop-picker';
import RNFetchBlob from 'react-native-fetch-blob'
import firebase from 'firebase';
const Blob = RNFetchBlob.polyfill.Blob
const fs = RNFetchBlob.fs
window.Blob = Blob
export const choozFile = (isSmalImg) => {
let options = {
width: isSmalImg ? 100 : 690,
height: isSmalImg ? 100 : 390,
cropping: true,
mediaType: 'photo'
};
return new Promise((resolve, reject) => {
ImagePicker.openPicker(options).then(response => {
let source = { uri: response.path };
resolve({ avatarSource: source, isProfileImg: isSmalImg })
})
});
}
export const addReportToFirebase = (obj = {}, uri, isProfile, mime = 'application/octet-stream') => {
obj["uId"] = "JtXNfy34BNRfCoRO6luwhIJke0l2";
const storage = firebase.storage();
const db = firebase.firestore();
const uploadUri = uri;
const sessionId = new Date().getTime();
let uploadBlob = null;
//keep reference to original value
const originalXMLHttpRequest = window.XMLHttpRequest;
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
const imageRef = storage.ref(`images${isProfile ? '/profile' : ''}`).child(`${sessionId}`)
fs.readFile(uploadUri, 'base64')
.then((data) => {
return Blob.build(data, { type: `${mime};BASE64` })
})
.then((blob) => {
uploadBlob = blob
return imageRef.put(blob, { contentType: mime })
})
.then(() => {
uploadBlob.close();
//revert value to original
window.XMLHttpRequest = originalXMLHttpRequest ;
imageRef.getDownloadURL().then((url)=>{
obj['image'] = url;
db.collection("reports").add(obj).then(() => {
console.log("Document successfully written!");
}).catch((err) => {
console.error("Error writing document: ", err);
});
})
})
.catch((error) => {
console.log('upload Image error: ', error)
})
};
that simple,,u can try this to upload image
<i>
getSelectedImages = (selectedImages, currentImage)=>{
const image = this.state.uri
let uploadBlob = null
let mime = 'image/jpg'
const originalXMLHttpRequest = window.XMLHttpRequest;
const originalBlob = window.Blob;
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
window.Blob = RNFetchBlob.polyfill.Blob
const imageRef = firebase.storage().ref('posts').child(this.state.uri)
RNFetchBlob.fs.readFile(image, 'base64')
.then((data) => {
return Blob.build(data, { type: `${mime};BASE64` })
})
.then((blob) => {
uploadBlob = blob
return imageRef.put(blob, { contentType: mime })
})
.then(() => {
uploadBlob.close()
window.XMLHttpRequest = originalXMLHttpRequest ;
window.Blob = originalBlob
return imageRef.getDownloadURL()
})
.then((url) => {
firebase.database().ref('groub').child(params.chat).child('message').push({
createdAt:firebase.database.ServerValue.TIMESTAMP,
image:url,
user:{
_id:params.id,
name:params.name,
},
})
alert('Upload Sukses')
})
.catch((error) => {
console.log(error);
})
}
</i>

Resources