首页 > 解决方案 > 角度,文件上传

问题描述

我在上传文件时遇到问题:html:

 <form #cv="ngForm" (ngSubmit)="onSubmit(cv.value)" (ngSubmit)="onUpload" class="form">
            <div ngModelGroup="curriculum" #curriculum="ngModelGroup">
                <div class="custom-file">
                    <label class="custom-file-label" for="file">Allega</label>
                    <div *ngIf="uploadResponse.status === 'error'">
                        {{ uploadResponse.message }}
                    </div>
                    <div *ngIf="uploadResponse.status === 'progress'">
                        <div role="progressbar" [style.width.%]="uploadResponse.message" aria-valuenow="25"
                            aria-valuemin="0" aria-valuemax="100">
                            {{uploadResponse.message}}%
                        </div>
                    </div>
                    <input ngModel type="file" name="upload" id="customFile" #curriculum1="ngModel" exportParts
                        (change)="onFileChange($event)" class="custom-file-input" (change)="log(curriculum)" placeholder="Upload file" accept=".pdf,.doc,.docx">
                </div>

上传.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpEvent, HttpErrorResponse,HttpClientModule, HttpEventType } from  '@angular/common/http';
import { map } from  'rxjs/operators';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';


@Injectable({
  providedIn: 'root'
})
export class UploadService {
  SERVER_URL: string = "http://localhost:4200";
  constructor(private httpClient: HttpClient) { }
  
  public upload(data, userId) {
    let uploadURL = `${this.SERVER_URL}/auth/${userId}/avatar`;

    return this.httpClient.post<any>(uploadURL, data, {
      reportProgress: true,
      observe: 'events'
    }).pipe(map((event) => {

      switch (event.type) {

        case HttpEventType.UploadProgress:
          const progress = Math.round(100 * event.loaded / event.total);
          return { status: 'progress', message: progress };

        case HttpEventType.Response:
          return event.body;
        default:
          return `Unhandled event: ${event.type}`;
      }
    })
    );
  }
}

第一页.component.ts

import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import {MatSliderModule} from '@angular/material/slider';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { Injectable } from '@angular/core';
import {HttpClient, HttpParams, HttpRequest, HttpEvent, HttpEventType, HttpResponse} from '@angular/common/http';
import {Observable} from "rxjs";
import { FormBuilder, FormGroup,Validators } from '@angular/forms';
import { UploadService } from  '../upload.service';

@Component({
  selector: 'first-page',
  templateUrl: './first-page.component.html',
  styleUrls: ['./first-page.component.css']
})
export class FirstPageComponent implements OnInit  {
  conoscenze:string[]=[];
  upload: any;
  appCfg: any;
  log(x){console.log(x);}
  submit(f){console.log(f);}

  
constructor(private formBuilder: FormBuilder, private cd: ChangeDetectorRef, private uploadService: UploadService)
 {
   this.form=this.formBuilder.group({
     upload:[this.upload]
   });
 }

form: FormGroup;
  error: string;
  userId: number = 1;
  uploadResponse = { status: '', message: '', filePath: '' };

  ngOnInit() {
    this.form = this.formBuilder.group({
      avatar: ['']
    });
  }

  onFileChange(event) {
    if (event.target.files.length > 0) {
      const file = event.target.files[0];
      this.form.get('upload').setValue(file);
    }
  }

  onUpload() {
    const formData = new FormData();
    formData.append('file', this.form.get('upload').value);

    this.uploadService.upload(formData, this.userId).subscribe(
      (res) => this.uploadResponse = res,
      (err) => this.error = err
    );
  }
}

我的目的是上传文件 .pdf 或 .docx 但实际上我无法回答自己为什么它不起作用:(。实际上我认为我做了所有的导入(也在 app.module.ts 中)。有办法更多代码,但它适用于实际工作的表单的其他部分。

控制台中的错误是:ERROR TypeError: Cannot read property 'setValue' of null

谢谢 :)

标签: angulartypescript

解决方案


不确定我是否在这里遗漏了什么。但是您似乎正在覆盖您在 ngOnInit 的构造函数中创建的表单。一旦涉及到 ngOnInit,formgroup 中就没有名为“upload”的表单控件了。因此,当您尝试在 onFileChange 方法中执行 setValue 时,它​​会失败

constructor(private formBuilder: FormBuilder, private cd: ChangeDetectorRef, private uploadService: UploadService)
 {
   this.form=this.formBuilder.group({
     upload:[this.upload]
   });
 }

form: FormGroup;
  error: string;
  userId: number = 1;
  uploadResponse = { status: '', message: '', filePath: '' };

  ngOnInit() {
    this.form = this.formBuilder.group({
      avatar: ['']
    });
  }

推荐阅读