Troubleshooting Problem with Uploading Several Photos to Firebase Storage

I need assistance with uploading multiple photos to Firebase Storage. Despite my efforts, it seems that the original upload keeps getting overwritten and the folder with the venueID property is not being created. Can someone provide some guidance on this issue?

app.js

async multiPhotoUpload(): Promise<any> {
    // Verify if there are photos to be uploaded.
    if (this.photosToUpload.length > 0) {
        const location = `venues/photos/${this.venueID}/`;
        // photosToUpload contains base64 strings.
        this.photosToUpload.forEach(async photoElement => {
            const randomID = this.venueService.createID();
            await this.uploadService.uploadFile(photoElement, location, true)
                .then(async data => {
                    const urlData = await data.ref.getDownloadURL();
                    const photoObject: Photo = {
                        fileName: `${this.venueID}${randomID}`,
                        url: urlData,
                        uploadedBy: this.currentUserID
                    };
                    await this.venueService.addPhoto(this.venueID, photoObject);
                },
                (err) => console.error(err));
        });
    } else {
        return;
    }
}

upload.service

uploadFile(file: any, path: string, base64?: boolean) {
    if (base64) {
        return this.uploadDB.ref(path).putString(file, 'data_url');
    } else {
        return this.uploadDB.upload(path, file);
    }
}

Answer №1

The issue here is that all the images are being saved in the same location within the firesotrage bucket due to setting up the location path prior to the forEach loop.

The corrected code snippet below will result in creating venues/photos/venueID/yourPictures

  // Check if there are any photos to be uploaded.
  if (this.photosToUpload.length > 0) {
    // photosToUpload is an array of base64 strings.
    this.photosToUpload.forEach(async photoElement => {
      const randomID = this.venueService.createID();
      const location = `venues/photos/${this.venueID}/${randomID}/`;
      // const location = `venues/photos/${this.venueID}/`; <---- The problem 
      //  const randomID = this.venueService.createID(); 
      await this.uploadService.uploadFile(photoElement, location, true)
        .then(async data => {
            const urlData = await data.ref.getDownloadURL();
            const photoObject: Photo = {
              fileName: `${this.venueID}${randomID}`,
              url: urlData,
              uploadedBy: this.currentUserID
            };
            await this.venueService.addPhoto(this.venueID, photoObject);
          },
          (err) => console.error(err));
    });
  } else {
    return;
  }
}

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

Discover the simple steps to include row numbers or serial numbers in an angular2 datagrid

Currently, I am utilizing angular2 -datatable. Unfortunately, I am facing an issue where the correct row numbers are not being displayed in their corresponding rows. Whenever a user moves to the next page using the paginator, the datatable starts countin ...

Exploring Angular: How to Access HTTP Headers and Form Data from POST Request

I am currently working with an authentication system that operates as follows: Users are directed to a third-party login page Users input their credentials The website then redirects the user back to my site, including an auth token in a POST request. Is ...

Encountering CORS Issue with Golang and Gin following a Redirect Situation

I am currently working on implementing Google OAuth2 in my Go web server using Gin. I have integrated two new endpoints - /google/sign-in and /google/callback. The former receives the request and redirects to the Google auth URL, while the latter is trigge ...

Using Stack and Drawer Navigations Together in React Native Navigation(v6)

I am looking to merge Stack and Drawer navigations. I have multiple screens and wish to display select screen labels in the drawer tab. <RootNavigatorStack.Navigator> <RootNavigatorStack.Screen name="DrawerTab" component={DrawerNavig ...

Issues with Cloud9 Angular and NodeJS connecting to API on a separate port of the same server

I am currently utilizing an AWS Cloud9 IDE for my project. Angular is running on port 8080, while my NodeJS (with Express) server is running on port 8081. In my Node app.js file, I have set up CORS headers as follows: const app = express(); app.use(expre ...

Avoiding the use of destructuring for undefined values in JavaScript can be achieved by implementing

Upon receiving the response registryReportSettings from the server: this.getRegistrySettings(registry.Id).subscribe((registryReportSettings: { extended: ReportPropertiesRequest }) => { const { objectProperties, reportProperties, textProperties } = reg ...

Is there a way to update the Angular component tag after it has been rendered?

Imagine we have a component in Angular with the selector "grid". @Component({ selector: 'grid', template: '<div>This is a grid.</div>', styleUrls: ['./grid.component.scss'] }) Now, when we include this gri ...

The Kendo Grid is refusing to show up within the popup window

I am new to using Angular 2 and Kendo UI. Currently, I am attempting to include a grid inside my pop-up window. While I have successfully displayed the pop-up, adding the grid has proven challenging. The grid is not appearing as expected ...

Exploring diverse paging methods tailored to specific devices within Angular 12

Hey there! I'm looking to implement two different paginations for a single table with 20 rows. Here's what I need: For desktop, the first pagination should display 10 rows on the first page and the remaining 10 rows on the second page. As f ...

Getting started with Angular 2 and initializing component variables

Hey there, I'm new to angular2 and currently facing a challenge. Here's the Service section: getReports() { return this.http.get(GlobalVariable.BASE_API_URL + 'report/l', {headers: this.headers}).map(res => res.json()) ...

The click listener triggers a single time when a render method is nested within it

When I have a click listener on a button that resets the innerHTML of a div with a render method, the listener fires every time I click if I take out the render function. However, if the render function is included, the listener does not fire multiple time ...

Issue with deploying Firebase Cloud Functions - Deployment Failed

Oh man, I am at my wit's end with this issue... Despite following all the correct steps for Firebase cloud functions, I keep encountering an error while trying to deploy: Build failed: Specified version range of module @firebase/app is not a strin ...

What is the best way to incorporate a WYSIWYG Text Area into a TypeScript/Angular2/Bootstrap project?

Does anyone know of a WYSIWYG text editor for TypeScript that is free to use? I've been looking tirelessly but haven't found one that meets my needs. Any recommendations or links would be greatly appreciated. Thank you in advance! ...

The specified type '{ songs: any; }' cannot be assigned to the type 'IntrinsicAttributes' in NEXTJS/Typescript

I am currently working on a straightforward script. Below is the index.tsx file for my Next.js application: import type { NextPage } from 'next' import SongsList from '../components/SongsList/SongsList' import { GetStaticProps } from & ...

Receiving warnings during npm installation and encountering difficulties with fixing issues using npm audit fix

Currently, I am working on developing an Angular application with a .NET Core Web API integration. Upon cloning the repository, I attempted to execute 'npm install' for the Angular application, but encountered an unexpected error: npm install n ...

What is the best way to make the current year the default selection in my Select control within Reactive Forms?

Hey there! I managed to create a select element that displays the current year, 5 years from the past, and 3 years from the future. But now I need to figure out how to make the current year the default selection using Reactive Forms. Any ideas on how to ac ...

Showing information from Flask API utilizing Angular with underscores

I'm in the process of creating components from my Flask API. Upon accessing the route, I can view the data for the desired objects. However, upon attempting to display it on the front end through interpolation, I am only able to see certain properties ...

What steps should I follow to set up a dynamic theme in an Angular Material application?

I have spent countless hours trying to find clear documentation on setting up an Angular Material app with a theme, including changing the theme dynamically. Despite searching through numerous search results and visiting various pages, I have not been able ...

Discovering the array item by its ID using Angular 2 with Typescript

Hey everyone, I'm currently working with asp.net mvc 5 and running into an issue. When attempting to retrieve an object by its id, it keeps returning undefined. The strange thing is that the objects display fine when checking console.log(this.vtypes). ...

What is the best way to receive a notification once the final observable has completed emitting its values?

In the past, we only made one call to the API reqFinanceDataWithFilters(req): Observable<any> { return this.http.post(env.baseUrl + req.url, req.filters) .pipe(map(this.extractResults)); } However, the response from this single request was a ...