ajgisme
ajgisme

Reputation: 1765

Uploading file to API whilst also sending other text fields - in Angular

I'm trying to upload a file to an API endpoint (built myself with Laravel) with an HTML form and it works when I'm just uploading the file. However I also want to send some basic text fields as part of the request.

The problem I'm finding is that some of the fields will be empty in which case "undefined" gets sent through in the request as a string which is not what I want of course, I'd just want the empty fields to send null or nothing at all.

I could add multiple if statements to first check if each field is not empty, but that doesn't feel very graceful. Is there a simple way to dynamically construct the form data object from whichever fields are present in the form?

Angular 2 code

This component launches a modal (which contains the form) and waits for when the modal is closed. When the modal is closed the component receives the "result" which would be an object with the fields from the form.

public openReferenceModal(): void {   
    dialogRef.afterClosed().subscribe(result => {    
        var fd = new FormData();
        fd.append('name', result.name);
        fd.append('phone_number', result.phone_number);
        fd.append('email_address', result.email_address);
        // This is the file that I'm uploading
        fd.append('document', result.document);

        this.addTeacherReference(fd);
    });
}

public addTeacherReference(item: any): void {
    this.teacherService
        .addTeacherReference(item)
        .subscribe(
            (reference) => {
                alert("Success!");
            }
        );
}

HTML markup for form in modal

<div>
    <mat-form-field>
        <input matInput placeholder="Name" [(ngModel)]="data.name" name="name" required>
        </mat-form-field>
    </div>

    <div class="mb-1">
        <mat-form-field>
            <input matInput placeholder="Phone number" type="phone" [(ngModel)]="data.phone_number" name="phone_number">
        </mat-form-field>
    </div>

    <div class="mb-1">
        <mat-form-field>
            <input matInput placeholder="Email address" type="email" [(ngModel)]="data.email_address" name="email_address">
        </mat-form-field>
    </div>

    <div class="pb-3">
        <h6>Upload Reference</h6>
        <input type="file" (change)="onFileChanged($event)">
    </div>

    <div>
        <button class="btn btn-secondary" [mat-dialog-close]="data">Save</button>
    </div>

Upvotes: 0

Views: 43

Answers (2)

peter554
peter554

Reputation: 1378

Another approach is the logical OR operator. For example, quoting your code:

var fd = new FormData();
fd.append('name', result.name || '');

This works because myObject.x || default is default if myObject.x is undefined (if not it simply returns myObject.x).

Upvotes: 0

abestrad
abestrad

Reputation: 916

You can set default form values. Form example here (taking a reactive form approach - https://angular.io/guide/reactive-forms):

// We inject the FormBuilder in our constructor
constructor(private fb: FormBuilder) {

    // Here we use the FormBuilder to build our form.
    this.complexForm = fb.group({
        // We set default values here.
        // For example, we set first and last name to the empty string ''.
        // And we set gender to 'female'.
        'firstName': '',
        'lastName': '',
        'gender': 'female',
        'hiking': false,
        'running': false,
        'swimming': false
    })
}

Upvotes: 1

Related Questions