Search code examples
angularng2-file-upload

Sending form data along with files upload in angular6 displays error title1 and title2 not found


This code uses ng2-file-upload in angular 6 to upload file and it works fine. Now I want to send form data along with the file.To this effect, I have added two form input title1 and title2 and here is how am implementing it the fileupload. This was line of code where I was implementing it. so I change the code below

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

to

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

but am having error src/app/app.component.ts cannot find title1 and title2 for the two form inputs..

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>

Solution

  • Issue

    You are trying to access the variable title1 and title2 which are not defined.

    Fix

    You have instance of AppData. You can use this directly instead.

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

    .

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

    Note : do not forget to set the title1 and title2 in data object.