I am trying to send a picture from my mobile hybrid app (Ionic 3) to my Heroku backend (Node.js) and have the backend upload the picture to Firebase Storage and return the newly uploaded fil download url to the mobile app.
Keep in mind that I am using the Firebase Admin SDK for Node.js.
So I send the base64 encoded image to Heroku (I check the encoded string with an online base64 decoder and it is alright) which is handle by the following function:
const uploadPicture = function(base64, postId, uid) { return new Promise((resolve, reject) => { if (!base64 || !postId) { reject("news.provider#uploadPicture - Could not upload picture because at least one param is missing."); } let bufferStream = new stream.PassThrough(); bufferStream.end(new Buffer.from(base64, 'base64')); // Retrieve default storage bucket let bucket = firebase.storage().bucket(); // Create a reference to the new image file let file = bucket.file(`/news/${uid}_${postId}.jpg`); bufferStream.pipe(file.createWriteStream({ metadata: { contentType: 'image/jpeg' } })) .on('error', error => { reject(`news.provider#uploadPicture - Error while uploading picture ${JSON.stringify(error)}`); }) .on('finish', (file) => { // The file upload is complete. console.log("news.provider#uploadPicture - Image successfully uploaded: ", JSON.stringify(file)); }); }) };
I have 2 major issues:
.on('finish)
, like in the upload()
function, but none is returned (file is undefined). How could I retrieve this url to send it back in the server response?I want to avoid using the upload()
function because I don't want to host files on the backend as it is not a dedicated server.
putString(your_base64_image, 'base64', {contentType:'image/jpg'}); Make sure to pass the metadata {contentType:'image/jpg'} as the third parameter (optional) to the function putString in order for you to retrieve the data in an image format. or simply put: uploadTask = firebase.
Set up firebase project Choose a name for your project. Firebase will then set up your project. For storing the files click on the “storage” button on the left navigation pane. Click “Get started” button, Then a modal will open which has the security rules for your cloud storage.
My problem was that I add data:image/jpeg;base64,
at the beginning of the base64 object string ; I just had to remove it.
For the download url, I did the following:
const config = { action: 'read', expires: '03-01-2500' }; let downloadUrl = file.getSignedUrl(config, (error, url) => { if (error) { reject(error); } console.log('download url ', url); resolve(url); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With