Enhancing file upload functionality in Angular 4 with a dual input event

I am facing an issue with uploading two input files as shown below:

<input required accept=".jpg" #file (change)="coverUpload($event)" id="file" name="file" type="file" >

<input required accept=".pdf" #pdf (change)="fileUpload($event)"  id="pdfFile" name="pdfFile" type="file" >



 <button md-raised-button color="primary" type="submit" (click)="addNew()" [disabled]="!form.valid">Submit</button>

Here is the TypeScript code snippet related to this:

selectedFiles: FileList;
selectedPdf: FileList;

coverUpload(event) {
      this.selectedFiles = event.target.files;
    }

fileUpload(event) {
      this.selectedPdf = event.target.files;
    }

 addNew() {

       let fle = this.selectedFiles.item(0);
       console.log(fle.name);
       let flePdf = this.selectedPdf.item(0);
       console.log(flePdf.name);

        this.bookSrv.addBook(this.books, fle, flePdf);
         this.router.navigate(['/mybooks']);
  }

And this is my BookService implementation:

 addBook(bok: Book, file: File, pdfFile: File) {
            if (this.uid != undefined && this.uid != null) {
                let key = this.afd.list('books' + '/' + 'list').$ref.ref.push().key;
                let userid = this.afAuth.auth.currentUser.uid;
                this.firebasestorage.ref(`books` + `/` + key + `/` + this.currentUserId + bok.bookname).put(file).then(
                this.firebasestorage.ref(`books` + `/` + key + `/` + this.currentUserId + bok.bookname).put(pdfFile).then(
                    snapshot => {
                        bok.icon = snapshot.downloadURL;
                        bok.pdf = snapshot.downloadURL;       
                        this.afd.object('books/list' + '/' + key + this.currentUserId).set(bok);
                    }));

            }
        }

However, after submitting it to Firebase, only the last uploaded file gets stored. Can anyone help me with how to upload both files simultaneously? Thank you.

Answer №1

give this a shot

 addBookToLibrary(book: Book, coverImage: File, pdfFile: File) {
        if (this.userId !== undefined && this.userId !== null) {
            let key = this.afd.list('books' + '/' + 'collection').$ref.ref.push().key;
            let userId = this.afAuth.auth.currentUser.uid;
            this.firebasestorage.ref(`books` + `/` + key + `/` + this.currentUserId + book.title).put(coverImage).then(
                snapshot => {
                    book.coverImageUrl = snapshot.downloadURL;
                    this.afd.object('books/collection' + '/' + key + this.currentUserId).set(book);
                });
             this.firebasestorage.ref(`books` + `/` + key + `/` + this.currentUserId + book.title).put(pdfFile).then(
                 snapshot => {
                    book.pdfUrl = snapshot.downloadURL;     
                    this.afd.object('books/collection' + '/' + key + this.currentUserId).set(book);
                });
        }
    }

Answer №2

It was discovered that the issue stemmed from the Book Service where it was necessary to separate the image and pdf folders in Firebase storage as shown below:

 addBook(bok: Book, cover: File, pdfFile: File) {
        if (this.uid != undefined && this.uid != null) {
            let key = this.afd.list('books' + '/' + 'list').$ref.ref.push().key;
            let userid = this.afAuth.auth.currentUser.uid;
            this.firebasestorage.ref(`cover` + `/` + key + `/` + this.currentUserId + bok.bookname).put(cover).then(
                snapshot => {
                    bok.cover = snapshot.downloadURL;      
                    this.afd.object('books/list' + '/' + key + this.currentUserId).set(bok);
                });
            this.firebasestorage.ref(`pdf` + `/` + key + `/` + this.currentUserId + bok.bookname).put(pdfFile).then(            
                snapshot => {
                    bok.file = snapshot.downloadURL;       
                    this.afd.object('books/list' + '/' + key + this.currentUserId).set(bok);
                    });    
        }
    }

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

Angular 2 Change Detection Issue: Value of expression has been updated post-check. Original value: 'over'. Updated value: 'side'

I'm encountering an error specifically in Firefox, but not in Chrome or IE. "Error: Error in ./DefaultLayoutComponent class DefaultLayoutComponent - inline template:2:14 caused by: Expression has changed after it was checked. Previous value: ' ...

Using the Angular Material DataTable in an Angular component, implement the SetTimeOut function within the ngOnInit lifecycle hook

While examining an Angular code snippet in one of my existing projects, I came across the following code. The page is rendered using Angular material datatable. export class Component implements OnInit,AfterViewInit{ private dataSource: MatTableDataSou ...

Position of the item in an array that contains an array with only one item

Currently, I am utilizing the Google Maps API in Angular with TypeScript. My goal is to create a clickable map of countries that changes color when clicked. This task seems simple, but I am encountering a challenge due to the complexity of the ng2-google-m ...

The TypeScript error message "Type 'x' cannot be assigned to type 'IntrinsicAttributes & IntrinsicClassAttributes<Class>'" was displayed on the screen

I encountered an issue when trying to pass a class method to a child component in a new code. While it worked perfectly in another code, I am now receiving the following error message: view image here What steps should I take to resolve this error? Do I ...

Talebook: Unable to modify UI theming color

As I embark on creating my own theme in Storybook, I am closely following the guidelines outlined here: Currently, I have copied the necessary files from the website and everything seems to be working fine. However, I am facing an issue when trying to cus ...

Avoid starting the stopwatch and timer at the same time

How can I control the timing of a user with a button? Currently, I can start multiple timers for different users at the same time. Is there a way to only start one timer at a time? I want the ability to pause the previous timer when starting a new one. I ...

Trouble with Angular 2 HTTP post: body not being transmitted correctly

I'm currently facing issues with the following code: var express = require('express'); var router = express.Router(); var mongojs = require('mongojs'); var db = mongojs('mongodb://lee:<a href="/cdn-cgi/l/email-protectio ...

Differences in Angular 2 Performance: Analyzing AOT and JIT Payloads

I'm still getting the hang of Angular 2, so feel free to correct me if I'm off base. Comparing Angular 1 and 2 in terms of the compiler: In Angular 1, the compiler is more general and dynamic, meaning that a single code is used for dirty checki ...

No updates found (Angular)

When a button is clicked, a test method is triggered with i as the index of an element in an array. The test method then changes the value of the URL (located inside the sMediaData object) to null or '' and sends the entire sMediaData to the pare ...

Leveraging jQuery within an Angular environment with TypeScript and Webpack

In my Angular (v2) project that utilizes TypeScript and Webpack, I initially used a starter project for seed. However, the configuration has been significantly modified to the point where referencing the source is irrelevant. Recently, I decided to incorp ...

Angular2's docking layout control brings a sleek interface that rivals Telerik's RadDocking

I've been utilizing Telerik's RadDocking control within my Silverlight projects. Unfortunately, I haven't been able to find a similar docking layout control for Angular2. The closest alternative I found was angular2-grid. https://www.npmjs. ...

The TypeScript error code TS2339 is indicating that the 'modal' property is not recognized on the type 'JQuery'

I'm currently utilizing Typescript with AngularJS and have encountered an issue with modals when using the typed definition of jQuery library. The specific error message I am receiving is: 'error TS2339: Property 'modal' does not exist ...

What is the reason for the HTTP service being activated automatically?

Utilizing the Http service, data is fetched and then passed into the cached service. The component subscribes to the cached service and initiates the HTTP request. The HTTP GET service is intended to be called when the user clicks on an anchor tag. Upon c ...

Encountered a hitch while trying to start an angular 2 app using npm

Encountering an error while compiling the application with @angular/cli version 1.2.4 @angular/cli: 1.2.4 node: 8.11.1 os: win32 x64 @angular/animations: 4.3.6 @angular/common: 4.3.6 @angular/compiler: 4.3.6 @an ...

Do we need a peer dependency specifically for TypeScript typings or is it optional?

My TypeScript library includes a React component, and one of the optional features allows users to pass an instance of a Redux store as a prop for Redux integration. <Component reduxStore={store}></Component> Since this feature is optional, I ...

Removing information from firebase with no timestamp recorded

Currently developing a survey application where I am storing data in the following format: Section1- James-"YYNN" JIM-"YN" Section2- Jamie-"NN" Sean-"YY" I need to set up automatic deletion for this data in Firebase after 30 days since I do not have ...

Comparing Synchronous Json with Asynchronous Json Responses

Currently, I have two functions that are capable of retrieving JSON data. searchAjax(url: any): any { let new_data: any; return $.ajax({ url: url, type: 'post', dataType: "json", async: false }).resp ...

Encounter an error during testing with jest where the issue arises from converting circular structure to JSON in moment.js on a specific line

While working with Angular and Jest, I encountered an error when incorporating moment.js into my code. Below is the import statement in my component: import * as moment from "moment"; The line where the error occurs: const date = moment(new Dat ...

Which Angular tools should I be using: map, pipe, or tap?

When my component initializes, I retrieve data from the server import {Rules} from "../../interfaces/interfaces"; rules: Rules ngOnInit() { this.tt = this.rulesService.getUserClientRules().subscribe( t => { console.log(t) con ...

How can we determine if a relative route is currently active in Angular?

In the component code, I can navigate to a route relative to the current route using this code snippet: this.router.navigate([item.route], {relativeTo: this.route}); When it comes to applying a highlight style in HTML based on the active route, I am faci ...