0

I would like to select a json file and parse it to an object before sending it to api call for validation. Below code is failing sending the formData. The api is expecting an object.

<label class="form-label required" for="file">File</label>
<label
    class="button secondary wide required"
    for="file"
    (click)="inputFileTarget.click()"
>
    Select JSON file
</label>
<input
    id="inputFileTarget"
    #inputFileTarget
    type="file"
    class="hidden"
    accept=".json"
    formControlName="fileInput"
    (change)="onFileChange($event)"
/>

component:

    const formData = new FormData();
    formData.append('file', this.importForm.get('fileSource').value);
    this.wizard.next();
    this.validateUploadedTemplate(formData);

private validateUploadedTemplate(formData: any): void {
    this.templateUploadService.validate(formData)
    .subscribe(result => {
        console.log('result', result);
    })
}



[HttpPost]
    [ResponseType(typeof(Boolean))]
    [Route("validate-definition", Name = "ValidateAuditTemplate")]
    [RequiredActivity(RadarModuleKeys.EnhancedAudits, EnhancedAuditActivities.ManageEnhancedAudits)]
    public async Task<IHttpActionResult> ValidateAuditTemplate(TemplateDefinition template)
    {


        return Ok(await Task.FromResult(true));
    }
Mukil Deepthi
  • 6,072
  • 13
  • 71
  • 156

1 Answers1

0

You can't just "read" the file like that. this.importForm.get('fileSource').value will return a FileList

interface FileList {
    readonly length: number;
    item(index: number): File | null;
    [index: number]: File;
}

Even if you set <input multiple="false" /> you will get a FileList with only one item.

If you only want one item then grab the first item from FileList and use FileReader to read the content.

Here is an answer that explains it: Read a file and parse its content

Salmin Skenderovic
  • 1,750
  • 9
  • 22