Multiple File Upload Using Angular 4

Discussão em 'Angular' iniciado por Rajesh Valluru, Dezembro 1, 2024.

  1. I am facing issue with multiple files upload using Angular 4.

    Here I am trying to append the multiple files in getFileDetails() but only file is selecting and if I choose another file it is getting replaced with the new file but actual expectation is they need to append each other and using post method I need to pass the json.

    app.component.html:

    <div>
    <h1>{{title}}!</h1>
    <ng-container>
    <input type="file" id="file" multiple (change)="getFileDetails($event)">
    <button (click)="uploadFiles()">Upload</button>
    </ng-container>
    </div


    app.component.ts

    import { Component, OnInit } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { HttpErrorResponse } from '@angular/common/http/src/response';

    @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
    })
    export class AppComponent {
    title = 'Upload Multiple Files in Angular 4';

    constructor (private httpService: HttpClient) { }


    ngOnInit () { }
    myFiles:string [] = [];
    sMsg:string = '';

    getFileDetails (e) {
    //console.log (e.target.files);
    for (var i = 0; i < e.target.files.length; i++) {
    this.myFiles.push(e.target.files);
    }
    }

    uploadFiles () {
    const frmData = new FormData();

    for (var i = 0; i < this.myFiles.length; i++) {
    frmData.append("fileUpload", this.myFiles);
    }

    this.httpService.post('url', frmData).subscribe(
    data => {
    // SHOW A MESSAGE RECEIVED FROM THE WEB API.
    this.sMsg = data as string;
    console.log (this.sMsg);
    },
    (err: HttpErrorResponse) => {
    console.log (err.message); // SHOW ERRORS IF ANY.
    }
    );
    }
    }
    }


    app.module.ts

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { AppComponent } from './app.component';

    import { HttpClientModule } from '@angular/common/http';

    @NgModule({
    declarations: [
    AppComponent
    ],
    imports: [
    BrowserModule,
    HttpClientModule
    ],
    providers: [],
    bootstrap: [AppComponent]
    })
    export class AppModule { }


    Expected json:

    [{
    "attachmentName": "content-infographic.txt",
    "attachedFile": ""
    },
    {
    "attachmentName": "infographic.png",
    "attachedFile": ""
    }]


    How can I correct the code to fix the issue?

    Continue reading...

Compartilhe esta Página