使用fom提交上传Angular4文件。?

时间:2017-09-11 06:40:25

标签: javascript angular angular-file-upload

这是我的.html文件

<form [formGroup]="complexForm" (ngSubmit)="submitForm(complexForm.value)">
    <div class="row">
        <div class="col-md-12 col-12">

            <label>My name is</label>
        </div>

        <div class="col-md-12 col-12 q-row">
            <div class="form-group" [ngClass]="{'has-error':!complexForm.controls['name'].valid && complexForm.controls['name'].touched}">
                <input class="form-control" type="text" [formControl]="complexForm.controls['name']">
                <div *ngIf="complexForm.controls['name'].hasError('required') && complexForm.controls['name'].touched" class="invalid">Please provide your name.</div>
            </div>
        </div>
    </div>

    <input type="file" (change)="fileChanged($event)" name="file1" [formControl]="complexForm.controls['file1']">
    <input type="file" (change)="fileChanged($event)" name="file2" [formControl]="complexForm.controls['file2']">
    <div class="form-group">
        <button type="submit" class="btn btn-primary pull-right">Submit</button>
    </div>

</form>

这是我的.ts文件

complexForm : FormGroup;
constructor(fb: FormBuilder){
   this.complexForm = fb.group({
        'name': [],
        'file1':[],
        'file2':[]
   });
}
 fileChanged(e: Event) {
   debugger;
    var target: HTMLInputElement = e.target as HTMLInputElement;
    for(var i=0;i < target.files.length; i++) {
      this.upload(target.files[i]);
    }
  }

  upload(uploads: File) {
    debugger
    var formData: FormData = new FormData();
    formData.append("files", uploads, uploads.name);
    console.log(formData);
}
  submitForm(values){
     console.log(values);
     console.log(FormData);
  }

但是在选择文件时,会调用上传函数,但是没有任何内容附加到formData.i只想在表单提交后上传文件。但是formdata的一些问题,虽然安慰它没有显示任何内容。在formbuild中它也不是显示任何解决方案吗?提前感谢。

1 个答案:

答案 0 :(得分:0)

首先,您要为每个文件调用upload,并在其中创建一个FormData的新实例。这意味着即使您尝试提交此表单,它也只会包含最后一个文件。

其次,您没有引用要提交的FormData实例,因为它是在上传函数范围内创建的override func viewDidLoad() { super.viewDidLoad() let button = UIButton(frame: CGRect(x: 0, y: 0, width: self.view.frame.width - 80, height: 30)) button.setTitle("Button", for: .normal) button.addTarget(self, action: #selector(showMainVC), for: .touchUpInside) let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width - 80, height: 30)) imageView.image = UIImage(named: "Image") let customView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width - 80, height: 30)) customView.addSubview(imageView) customView.addSubview(button) self.navigationItem.titleView = customView } func showMainVC() { //TODO: } 。因此,它在submitForm函数中不可用。您尝试记录的是FormData的Object原型,它不包含任何有用的信息。

要再试一次,您需要重构代码:

var formData: FormData = new FormData();