0

此代码使用Angular 6中的ng2-file-upload来上传文件,并且工作正常。现在我想将表单数据与文件一起发送。为此,我添加了两个表单输入title1title2,这是文件上传的实现方式。这是我实现它的代码行。所以我更改了下面的代码

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

应用数据.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>
4

1 回答 1

0

问题

您正在尝试访问未定义title1的变量。title2

使固定

你有AppData. 您可以直接使用它。

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

.

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

注意:不要忘记设置title1and title2indata对象。

于 2018-10-21T03:49:26.570 回答