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

前端 未结 3 889
有刺的猬
有刺的猬 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

        
        

    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);
    }
    

提交回复
热议问题