首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Angular,文件上传

Angular,文件上传
EN

Stack Overflow用户
提问于 2020-07-02 18:37:16
回答 1查看 38关注 0票数 0

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

代码语言:javascript
复制
 <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>

upload.service.ts

代码语言:javascript
复制
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}`;
      }
    })
    );
  }
}

first-page.component.ts

代码语言:javascript
复制
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属性'setValue‘of null

谢谢您:)

EN

Stack Overflow用户

回答已采纳

发布于 2020-07-02 19:22:38

我不确定我是不是错过了什么。但是您似乎覆盖了您在ngOnInit的构造函数中创建的表单。一旦涉及到ngOnInit,在表单组中就没有叫做"upload“的表单控件。因此,当您尝试在onFileChange方法中执行setValue时,它会失败

代码语言:javascript
复制
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: ['']
    });
  }
票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62694413

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档