Search code examples
angulartypescriptkendo-uikendo-ui-angular2

Kendo Angular upload file with other JSON parameters


I am using KendoUI in our Angular application and we need to upload a file to backend with other details like username,description,uploadtypeid as shown in below figure enter image description here

I have checked with available kendo upload feature available , but it accepts only file to upload .How can I make changes to below stackblitz so I can accommodate other request body parameters.

kendo-upload


Solution

  • In my opinion, a solution for this issue would be to handle the form yourself, rather than letting the control perform the file upload. You should start by setting autoUpload to false, to prevent the control from uploading the image immediately after the file(s) are selected. Then you can manually handle the select and also the remove events to get control of the files that the user is selecting, then build your own payload with the files and the rest of the fields:

    <kendo-upload
      [autoUpload]="false"
      (select)="handleFileSelected($event)"
      (remove)="handleFileRemoved($event)">
    </kendo-upload>
    

    In your .ts you should have a field to keep track of the files, and the handlers for the select and remove events:

    private files: FileInfo[] = [];
    
    handleFileSelected(event: SelectEvent) {
      const newFiles = event.files.filter(
        (f) => !this.files.find((existingFile) => existingFile.name == f.name)
      );
      this.files = [...this.files, ...newFiles];
    }
    
    handleFileRemoved(event: RemoveEvent) {
      this.files = this.files.filter((f) => event.files.indexOf(f) === -1);
    }
    

    From your screenshot, I can see you only need one file, so the handlers could become simpler:

    private file: FileInfo;
    
    handleFileSelected(event: SelectEvent) {
      this.file = event.files.slice().shift();
    }
    
    handleFileRemoved(event: RemoveEvent) {
      this.file = null;
    }
    

    Then you can pass the file to your save method in your service:

    handleSave() {
      this.service.saveUpload(
        this.uploadTypeId,
        this.description,
        this.uploadedUserId,
        this.file?.rawFile
      ).subscribe(res => {
        console.log('successfully saved', res);
      }
    }