Issues encountered when trying to upload images to Firestore Storage

I am attempting to upload an image and store its URL in a Firestore document. To achieve this, I have the following code snippet:

This function uses the device camera to capture the photo.

selectImage(): Promise<any> {
    return new Promise(resolve => {
        let cameraOptions: CameraOptions = {
            destinationType: this.camera.DestinationType.DATA_URL,
            encodingType: this.camera.EncodingType.JPEG,
            correctOrientation: true
        };

        this.camera.getPicture(cameraOptions)
            .then((data) => {
            this.cameraImage = "data:image/jpeg;base64," + data;
            resolve(this.cameraImage);
        });
    });
}

The next step involves uploading the image and updating the document with the generated URL.

uploadProfilePhoto() {
    console.log(this.cameraImage)
    if (this.cameraImage != null) {


        this.image = 'profilePhoto' + new Date().getTime() + '.jpg';
        let storageRef: any;
        let parseUpload: any;
        storageRef = firebase.storage().ref('profilePhotos/' +
        this.image);
        parseUpload = storageRef.putString(this.cameraImage,
        'data_url');
        let ID = firebase.auth().currentUser.uid;
        console.log("ID")
        console.log(ID);
        parseUpload.on('state_changed', (snapshot) => {
            // Upload completed successfully, now we can get the
            download URL
            snapshot.ref.getDownloadURL().then((downloadURL) => {
                let profilePhoto = downloadURL
                this.firestore.doc(`users/${ID}`).update({
                    profilePhoto
                })
            });

        })
    }
}

Despite successful image uploads, there are instances where the document update does not occur, leading to the error message:

Failed to load resource: the server responded with a status of 404

Upon inspection of the link in the error message, it appears as shown here.

This error occurs consistently whenever the code is executed, appearing multiple times per operation.

Answer №1

It seems that the error message you received is a "404", which is commonly known as an HTTP response code indicating that the requested file was not found. This error occurs when calling getDownloadURL, signaling that the file is not available because it has not finished uploading.

After using storageRef.putString(), the file upload process has not yet begun. By referring to the API documentation provided, you'll notice that this method returns an UploadTask object, similar to a Promise with a then() method. Utilize this UploadTask to track the completion of the upload process before expecting getDownloadURL to function correctly.

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

The behavior of K6 test execution capabilities

Hey there, I'm new to K6 and I've got a query about how tests are executed. Take this small test with a given configuration for example: export const options = { stages: [ { target: 10, duration: '30s'} ]} When I run the test with ...

Having trouble getting Ionic to install on node.js?

Encountering an issue with the installation of ionic framework: https://i.stack.imgur.com/o587q.png Operating system: Windows 10 Node.js version: 7.4 Npm version: 4.0.5 Npm installation completed successfully. Cordova installation also went smoothly. S ...

Exploring the filter method in arrays to selectively print specific values of an object

const array = [ { value: "Value one", label: "Value at one" }, { value: "Value 2", label: "Value at 2" }, { value: "" , label: "Value at 3" } ...

pick only one option from each row

I am working on a feature where I have five rows with two checkboxes each generated using a loop and property binding. Currently, clicking on one checkbox selects all elements in the column. However, I want to achieve selection row-wise. Is there a method ...

Disabling FormArray on-the-fly in Angular

I have a scenario where I need to disable multiple checkboxes in a FormArray when the page loads. Despite my attempts to implement this, it hasn't been successful so far. Can someone provide guidance on how to achieve this? .ts file public myForm: Fo ...

Having trouble triggering the button with querySelector in Angular

I have a dynamic page where I need to click on a button. I tried the code below, but it is not working and not showing any alert. However, if we use the same code in the browser console, it executes and shows an alert. Can someone please suggest how to r ...

Investigating the issue: Why is my React Typescript canvas image resizing component producing small, fuzzy images from high-quality, large images

I have developed a small image resizer but am facing an issue with the output images being blurry, especially when working with large images. import React, { useState } from 'react'; interface PropsInterface { placeholder: string; resizeTo: ...

Angular 2/4 - Saving User Object Information in the Front-End Instead of Repeatedly Contacting the Back-End Server

Is there a more efficient way to store and update the current user details in the frontend, without constantly making new HTTP GET requests to the backend every time a new component loads? The solution I came up with is a UserService class that handles se ...

Zod combinator that accepts a dynamic field name

When converting XML to JSON, my library outputs {MyKey: T} for single-element lists and {MyKey: T[]} for multi-element lists. The equivalent TypeScript type is type XmlJsonArray<T, element extends string> = Record<element, T | T[]>. To implemen ...

What is the optimal method for navigating through a complex nested object in Angular?

Looking to navigate through a nested object structure called purchase. Within this structure, there is a sub-array named purchaseProducts which contains another sub-array called products along with additional data. What methods do you suggest for efficien ...

Nextjs build: The specified property is not found in the type 'PrismaClient'

I have a NextJS app (TypeScript) using Prisma on Netlify. Recently, I introduced a new model named Trade in the Prisma schema file: generator client { provider = "prisma-client-js" } datasource db { provider = "postgresql" url ...

How to avoid truncating class names in Ionic 4 production build

I have been working on an ionic 4 app and everything was going smoothly until I encountered an issue with class names being shortened to single alphabet names when making a Prod build with optimization set to true. Here is an example of the shortened clas ...

Challenges in mimicking the search functionality of Angular's Tour of Heroes due to issues with Observers

I'm facing an issue while trying to incorporate a search bar with autocomplete suggestions in Angular 9. It worked perfectly in the tour of heroes tutorial, but when I attempt to replicate it, the searchTerms pipe seems to be inactive (the service is ...

Developing an object using class and generic features in Typescript

I am currently working on creating a function or method that can generate sorting options from an array. One example is when using Mikro-ORM, where there is a type called FindOptions<T> that can be filled with the desired sorting order for database q ...

Why isn't the customer's name a part of the CFCustomerDetails class?

Currently, I am utilizing the cashfree-pg-sdk-nodejs SDK to integrate Cashfree payment gateway into my application. Upon examining their source code, I noticed that the CFCustomerDetails class does not include the customerName attribute. https://i.stack.i ...

Template URI parameters are being used in a router call

Utilizing the useRouter hook in my current project. Incorporating templated pages throughout the application. Implementing a useEffect hook that responds to changes in the router and makes an API call. Attempting to forward the entire URL to /api/${path ...

Utilizing Dual Destructuring for Handling Undefined Main Objects

Before we proceed, I want to clarify that my question is not a duplicate of ES6 double destructure Let's examine the code snippet related to Apollo Client GraphQL: import { gql, useQuery, useMutation } from '@apollo/client'; ... const { loa ...

Angular integration problem with aws-amplify when signing up with Google account

I am attempting to integrate AWS-Amplify(^4.3.0) with angular-12 and typescript (4.3.5). I have followed the documentation to configure amplify properly, but when trying to start the app, I encountered some amplify errors as shown below. Warning: D:\G ...

Error encountered in ngtsc(2345) where an argument of type 'Event' is being used instead of an expected parameter type of 'SortEvent'

I recently started using angular and encountered an issue while trying to sort columns. The error message I received was: Argument of type 'Event' is not assignable to parameter of type 'SortEvent'. Type 'Event' is missing t ...

FirebaseError: The type 'Hc' was expected, but instead, a custom Yc object was provided

I've encountered an issue while attempting to perform a batch entry. The error I'm facing involves passing an array in a .doc file. Interestingly, this approach seems to work perfectly fine on another function where I pass an array into a .doc us ...