Ionic & Firebase Image Upload Example

Firebase Realtime, Cloud Firestore & Storage

File Upload By The Books

uploadToFirebase(_imageBlobInfo) {
console.log("uploadToFirebase");
return new Promise((resolve, reject) => {
let fileRef = firebase.storage()
.ref("images/" + _imageBlobInfo.fileName);
let uploadTask = fileRef.put(_imageBlobInfo.imgBlob); uploadTask.on(
"state_changed",
(_snap: any) => {
console.log(
"progess " +
(_snap.bytesTransferred / _snap.totalBytes) * 100
);
},
_error => {
console.log(_error);
reject(_error);
},
() => {
// completion...
resolve(uploadTask.snapshot);
}
);
});
}

Magic of converting image from camera to blob for upload

const options: CameraOptions = {
quality: 80,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
};
let cameraInfo = await this.camera.getPicture(options);
// FILE STUFF
makeFileIntoBlob(_imagePath) {
// INSTALL PLUGIN - cordova plugin add cordova-plugin-file
return new Promise((resolve, reject) => {
let fileName = "";
this.file
.resolveLocalFilesystemUrl(_imagePath)
.then(fileEntry => {
let { name, nativeURL } = fileEntry;
// get the path..
let path = nativeURL
.substring(0, nativeURL.lastIndexOf("/"));
fileName = name; // we are provided the name, so now read the file
// into a buffer
return this.file.readAsArrayBuffer(path, name);
})
.then(buffer => {
// get the buffer and make a blob to be saved
let imgBlob = new Blob([buffer], {
type: "image/jpeg"
});

// pass back blob and the name of the file for saving
// into fire base
resolve({
fileName,
imgBlob
});
})
.catch(e => reject(e));
});
}

Things to notice in the code

  "@ionic-native/camera": "^5.0.0-beta.15",
"@ionic-native/core": "^5.0.0-beta.17",
"@ionic-native/file": "5.0.0-beta.15",
"@ionic-native/splash-screen": "5.0.0-beta.15",
"@ionic-native/status-bar": "5.0.0-beta.15",
// notice the path for the import ends in ngx
import { Camera, CameraOptions } from "@ionic-native/camera/ngx";
import { File } from "@ionic-native/file/ngx";
import { Camera } from '@ionic-native/camera/ngx';
import { File } from '@ionic-native/file/ngx';
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
providers: [
File,
Camera,
StatusBar,
SplashScreen,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
export class AppModule {}

Full Source Code To Example:

DC based software agency utilizing #Javascript, #Typescript, #HTML5, #Ionicframework, #NodeJS, #Firebase to build web & mobile solutions. https://buff.ly/300Zru

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store