【问题标题】:Sending form data along with files upload in angular6 displays error title1 and title2 not found发送表单数据以及 angular6 中上传的文件显示错误 title1 和 title2 not found
【发布时间】:2019-03-25 09:32:36
【问题描述】:

此代码使用 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');
        };
    }
}

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>

【问题讨论】:

  • 试试additionalParameter: {t1: data.title1, t2: data.title2 });

标签: angular ng2-file-upload


【解决方案1】:

问题

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

修复

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

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

.

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

注意:不要忘记在data对象中设置title1title2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    • 2020-02-10
    • 2013-06-18
    • 1970-01-01
    相关资源
    最近更新 更多