发送表格数据以及在angular6中上传的文件时,显示错误title1和title2

时间:2018-10-20 21:16:56

标签: angular ng2-file-upload

此代码使用角度6 中的 ng2-file-upload 上传文件,效果很好。现在我想将表单数据与文件一起发送。为此,我添加了两个表单输入 title1 title2 ,这是实现文件上传的方法。这是我实现它的代码行。所以我更改下面的代码

public uploader: FileUploader = new FileUploader({ url: URL, itemAlias: 'photo' });

public uploader: FileUploader = new FileUploader({url: URL, itemAlias: 'photo', 
 additionalParameter: {
        t1: title1, t2: title2 });

但出现错误src / app / app.component.ts找不到两个表单输入的title1和title2

app.component.ts

import { Component, OnInit } from '@angular/core';
import { FileUploader, FileSelectDirective } from 'ng2-file-upload/ng2-file-upload';

const URL = 'http://localhost:3000/api/upload';

import { AppData } from './AppData';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
    title = 'app';

    public uploader: FileUploader = new FileUploader({ url: URL, itemAlias: 'photo' });

/*
public uploader: FileUploader = new FileUploader({url: URL, itemAlias: 'photo', 
 additionalParameter: {
        t1: title1, t2: title2
  */


 data = new AppData('', '');    

    ngOnInit() {
        this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; };
        this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {
            console.log('ImageUpload:uploaded:', item, status, response);
            alert('File uploaded successfully');
        };
    }
}

AppData.ts

export class AppData {
  constructor(
      title1: String,
      title2: String
  ) {}
}

app.component.html

    <input type="file" name="photo" ng2FileSelect [uploader]="uploader" />

    <input type="text" class="form-control" id="title1" 
      required
      [(ngModel)]="data.title1"/>

    <p>Hello {{data.title1}}!</p>        

    <input type="text" class="form-control" id="title2" 
      required
      [(ngModel)]="data.title2"/>

    <p>Hello {{data.title2}}!</p>

<button type="button" class="btn btn-success btn-s" 
 (click)="uploader.uploadAll()"
  [disabled]="!uploader.getNotUploadedItems().length" >
      Upload an Image
</button>

1 个答案:

答案 0 :(得分:0)

问题

您正在尝试访问未定义的变量title1title2

修复

您有AppData的实例。您可以直接使用它。

data = new AppData('', '');  

public uploader: FileUploader = new FileUploader({url: URL, itemAlias: 'photo', 
additionalParameter: this.data
  

注意:不要忘记在title1对象中设置title2data