How to include a file upload control in an Angular2 reactive form?

前端 未结 3 888
有刺的猬
有刺的猬 2020-12-08 14:42

For some weird reason, there are just no tutorials or code samples online showing how to use Angular2 Reactive forms with anything more than simple input or select dropdowns

相关标签:
3条回答
  • 2020-12-08 15:02

    Simple answer can be found here. https://devblog.dymel.pl/2016/09/02/upload-file-image-angular2-aspnetcore/

    The HTML

        <input #fileInput type="file"/>
        <button (click)="addFile()">Add</button>

    Component.ts

    @ViewChild("fileInput") fileInput;
    
    addFile(): void {
    let fi = this.fileInput.nativeElement;
    if (fi.files && fi.files[0]) {
        let fileToUpload = fi.files[0];
        this.uploadService
            .upload(fileToUpload)
            .subscribe(res => {
                console.log(res);
            });
        }
    }
    

    The service.ts

    upload(fileToUpload: any) {
        let input = new FormData();
        input.append("file", fileToUpload);
    
        return this.http.post("/api/uploadFile", input);
    }
    
    0 讨论(0)
  • 2020-12-08 15:05

    I'm a bit late to this, but for anyone else that may come here looking for the same solution - This is my file input accessor that can be used with Reactive or Template-driven forms. Demo here.

    There's some optional validation provided with it that can be used to check image dimensions and file size, extension, type, which is disabled by default.

    npm i file-input-accessor and add the module to your AppModule imports:

    import {BrowserModule} from '@angular/platform-browser';
    import {FileInputAccessorModule} from "file-input-accessor";
    
    @NgModule({
        declarations: [
            AppComponent
        ],
        imports: [
            BrowserModule,
            FileInputAccessorModule
        ],
        providers: [],
        bootstrap: [AppComponent]
    })
    export class AppModule {}
    

    Then use your file input like any other input:

    <!--Reactive Forms-->
    <input type="file" multiple [formControl]="someFileControl" />
    <input type="file" multiple formControlName="someFileControl" />
    
    <!--Template-driven-->
    <input type="file" name="file-input" multiple [(ngModel)]="fileList" />
    

    You can subscribe to valueChanges property just like any other reactive control.

    0 讨论(0)
  • 2020-12-08 15:20

    You can use the below method to upload image in any type of form.

    Expose one change method to your control.

    <input class="form-control" type="file" name="avatar" (change)="imageUpload($event)">
    <img [src]="imageUrl" />
    

    Add below logic in your class.

     // Declare the variable. 
      imageUrl: any;
    
       //method definition in your class 
        imageUpload(e) {
            let reader = new FileReader();
            //get the selected file from event
            let file = e.target.files[0];
            reader.onloadend = () => {
              //Assign the result to variable for setting the src of image element
              this.imageUrl = reader.result;
            }
            reader.readAsDataURL(file);
          }
        }
    

    Once the image is uploaded you can use the this.imageUrl to update your form model. For uploading the image or file to server you can take the reference from the below link.

    How to upload file in Angular2

    Let me know if this solution is working for you.

    0 讨论(0)
提交回复
热议问题