Utilizing Firebase 3 with Ionic 2 and cordova-plugin-camera for seamless file uploading

I have been attempting to upload images to Firebase storage using the cordova-plugin-camera but have not been successful:

Below is the code I have been using:

let options:any = {
    quality : 100,
    destinationType : Camera.DestinationType.DATA_URL,
    sourceType : Camera.PictureSourceType.CAMERA,
    allowEdit : false,
    encodingType: Camera.EncodingType.JPEG,
    mediaType: Camera.MediaType.PICTURE,
    targetWidth: 1920,
    targetHeight: 1920,
    saveToPhotoAlbum: true,
    cameraDirection: Camera.Direction.FRONT
};

Camera.getPicture(this.options).then( (imageData) => {

                let blob: any = new Blob( [imageData], { type: "image/jpeg" } );
                blob.name = 'image.jpg';

                let storageRef: any = firebase.storage().ref();
                let path: string = 'images/' + this.user.uid + '/' + Math.random().toString(36).substr(2, 9) + '.jpg';

                console.log(path);

                let uploadTask: any = storageRef.child(path).put(blob);

                uploadTask.on('state_changed', function(snapshot) {
                    console.log(snapshot);
                }, function(error) {
                    this.showAlert(error);
                }, function() {
                    var downloadURL = uploadTask.snapshot.downloadURL;
                    console.log(downloadURL);

                    console.log(this.user);

                    this.user.set({photo: downloadURL});
                });

            }, (err) => {
                this.showAlert(err);
            });

For some reason, the file seems to upload but when I check, it is empty.

Any assistance would be greatly appreciated.

Thank you.

Answer №1

The issue lies within this section

let imageBlob: any = new Blob([imageData], { type: "image/jpeg" });

You must convert the imageData from base64 to a Blob. I recommend using the atob function as shown in this reference https://example.com/12345678/9876543 to create the Blob. This solution successfully resolved the same problem I encountered.

However, keep in mind that DATA_URL can consume a lot of memory, especially with larger image files.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

PhpStorm IDE does not recognize Cypress custom commands, although they function properly in the test runner

Utilizing JavaScript files within our Cypress testing is a common practice. Within the commands.js file, I have developed a custom command: Cypress.Commands.add('selectDropdown', (dropdown) => { cy.get('#' + dropdown).click(); } ...

Searching for a particular Prettier setting

Seeking a Nicer alternative. I am exploring if there is a way to format code like this without moving the first attribute to a new line: <div class="test-class" [test-binding]="true" (test-binging)="test()" ...

Modifying a chosen row within a table using Angular

Currently, I am working on developing a To-Do list application using Angular 11. The application includes a Bootstrap table where data is displayed upon clicking the add button. Each row in the table contains icons for delete, edit, save after editing, and ...

Using TypeScript with Angular: encountering a ReferenceError stating that the System object is not defined in the System

I attempted to follow a tutorial to set up Angular 2 with TypeScript from the following link: https://angular.io/guide/quickstart However, I encountered the following error: ReferenceError: System is not defined System.config I am uncertain why this e ...

How can an Angular Component be created in the browser using the standard method?

Attempting to develop a basic Angular example using JS/ESM. It has been some time since working within the angular environment, and there appear to be two primary choices: Utilizing the UMD lib (preferably to be avoided) Using the ESM2015 folder and loadi ...

Single array returned by observable

Issue: I am looking for a way to consolidate the multiple arrays returned individually into a single array. Solution: fetchAllRiders() { var distanceObs = Observable.create(observer => { this.http.get(this.API + '/driver/all').map(res = ...

What is the best way to create Jest unit tests for an Angular Component without using TestBed?

I'm diving into the world of Jest testing and feeling lost as to why my tests keep failing. If you have any recommendations for videos or articles that focus on writing Jest unit tests for Angular components and services without using "TestBed," plea ...

Firestore Cloud Function Automatically Terminates during Invocation

I have set up a custom endpoint for my FireStore database. Currently, I am attempting to log all values to the console when called from a client. However, when I make the request, it times out and the console displays the following message: @firebase/da ...

Encountering issues following the integration of @angular/flex-layout into an Angular project

After careful consideration, I opted to utilize the responsive grid system provided by @angular/flex-layout instead of Bootstrap. By simply installing the npm package and adding it to my AppModule, I was able to integrate it seamlessly: import { NgModule ...

What is the best way to center all items in a vertical list of text?

Having trouble aligning elements in my Angular app - specifically date, file total, and file size. When one number has more digits than the others, it throws off the alignment. I've attempted adjusting padding margins and using display properties lik ...

What is the best way to create a TypeScript type for React props that only allows prop B to be used if prop A is included in the component?

My component Text has 2 props: isHideable: boolean and hidden: boolean. How can I only allow Hidden as a prop when isHideable is set to true? Currently, both isHideable and hidden are being accepted which is not the desired behavior: type Props = { chi ...

Displaying information in a table using Angular, instead of displaying it directly from

I'm currently developing an Angular application that utilizes ngx-datatable for displaying data. In this case, I have a Supplier object that needs to be shown in a table using ngx-datatable, with some columns displaying object properties and others sh ...

Retrieve the selected rows in AG grid based on their group index

Important: The data in the grid is organized into groups. I am attempting to retrieve selected rows at a specific group index. I have attempted using the getDisplayedRowAtIndex(index).allLeafChildren method and looping through each node to find those tha ...

creating a new date instance with a specific time zone

Creating a Date object with a dynamically selected timezone is my current goal while I am located in the IST time zone. To avoid the unpredictable behavior of Date.parse(), I am looking for an alternative method. Let's say we set the tzOffset to +05:3 ...

Using Typescript to typecast in D3.js

Utilizing the D3 graph example available here. I've defined my data object as shown below: interface ID3Data { age: string, population: number } const data: ID3Data[] = [ { age: "<5", population: 2704659 }, { age: "5-13", population: 4499 ...

What is the best way to conditionally render one of several components in a manner that is compatible with React's change detector?

Within my CRUD application, I have incorporated various reusable components such as a "generic" DialogComponent, along with several non-reusable components. Throughout the development process, I have encountered numerous instances where I need to either: ...

Determine the data type of a class property by referencing the data type of a different property within the

Why am I getting an error when assigning to this.propertyB in TypeScript? class Example { public readonly propertyA: boolean; private readonly propertyB: this['propertyA'] extends true ? null : 'value'; public constructor() ...

Angular rxjs Distinctions

Coming from AngularJS to Angular, I'm still trying to wrap my head around rxjs observable. For example: User.ts export class User { id?:any; username:string; password:string; } Using <User[]> myUser(header: any) { const url = `${this.mainUr ...

Is there a way for me to properly type the OAuthClient coming from googleapis?

Currently, I am developing a nodemailer app using Gmail OAuth2 in TypeScript. With the configuration options set to "noImplicitAny": true and "noImplicitReturns": true, I have to explicitly define return types. Here is a snippet of my code: import { goog ...

Steps for appending a string to a variable

Currently working on creating a price configurator for a new lighting system within homes using Angular 7. Instead of using TypeScript and sass, I'm coding it in plain JavaScript. Page 1: The user will choose between a new building or an existing one ...