Skip to content

Instantly share code, notes, and snippets.

@kaleidawave
Created July 6, 2019 19:07
Show Gist options
  • Save kaleidawave/3ff8b2ddb2990237f354bd7a48ef5326 to your computer and use it in GitHub Desktop.
Save kaleidawave/3ff8b2ddb2990237f354bd7a48ef5326 to your computer and use it in GitHub Desktop.
Pass image files through firebase function arguments
exports.uploadImage = functions.https.onCall(async (data, context) => {
const mimeType = data.image.match(/data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+).*,.*/)[1];
const base64EncodedImageString = data.image.replace(/^data:image\/\w+;base64,/, '');
const imageBuffer = new Buffer(base64EncodedImageString, 'base64');
const filename = `posts/${data.name}.${mimeTypes.detectExtension(mimeType)}`;
const file = admin.storage().bucket().file(filename);
await file.save(imageBuffer, { contentType: 'image/jpeg' });
const photoURL = await file.getSignedUrl({ action: 'read', expires: '03-09-2491' }).then(urls => urls[0]);
return { photoURL };
});
<input type="file" id="image-input" value="upload" accept="image/jpeg"/>
<button onclick="submit()"> Upload </button>
let base64image = '';
let reader = new FileReader();
document.getElementById('image-input').addEventListener('change', ev => {
reader.readAsDataURL(ev.target.files[0]);
});
reader.addEventListener("load", function () {
base64image = reader.result;
}, false);
function submit() {
firebase.functions().httpsCallable('uploadImage')({ name: 'Image Name', image: base64image });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment