0

We're implementing kendo for angular in our project. We have an existing project that is using kendo-upload which immediately fires a call to the server, but I can't do that for this page.

Screenshot

The page is for an employee to upload a resume. They may have an existing resume and will need to be asked if they want to replace it first, and they are given a field for entering a description. Thus, I think I need to use kendo-fileselect and potentially trigger a dialog (are you sure you want to replace?), and send along the description and employee's ID on a button click. So I've created an object to carry this data.

You can see that the object is populated when it calls the API:

Debugging Resume

But when I try to call the API method, I get an error:

Failed to load resource: the server responded with a status of 400 (Bad Request) [http://localhost:6300/api/employee/resume]

Error Details

Relevant code is below.

Server-side:

public class EmployeeResume
{
    public int ResumeId { get; set; }
    public int EmployeeId { get; set; }
    public DateTime CreatedDate { get; set; }
    public string Description { get; set; }
    public byte[] FileContent { get; set; }
    public string FileName { get; set; }
}

[HttpPut("resume")]
    public async Task<IActionResult> UploadResume([FromBody] EmployeeResume resume)
    {            
        if (resume == null)
        {
            return BadRequest();
        }


        return Ok();
    }

Client-side:

// Model
export interface EmployeeResume {
    createdDate?: string;
    description?: string;
    employeeId: string;
    fileContent: any;
    fileName: string;    
    resumeId?: string;
}

// CHILD component
// -----------------------------------------------------------

// Kendo FileSelect in template
<kendo-fileselect
    formControlName="uploadFile"
    [restrictions]="uploadRestrictions"
    [multiple]="false"
    (select)="selectEventHandler($event)">
</kendo-fileselect>

// Sets a component property to the selected file
selectEventHandler(e: SelectEvent): void {
    this.uploadfile = e.files[0];
}

// When upload button is clicked, create the
// resume object and emit an event to parent
upload(): void {

    if (this.uploadfile.validationErrors) return;

    const thisComponent = this;
    const reader = new FileReader();

    reader.onload = function (ev) {
      const request = {
        description: thisComponent.f.description.value,
        employeeId: thisComponent.employeeId,
        fileContent: ev.target.result,
        fileName: thisComponent.uploadfile.name
      } as EmployeeResume;

      thisComponent.onUpload.emit(request);
    }

    reader.readAsDataURL(this.uploadfile.rawFile);    
}

// PARENT component
// -----------------------------------------------------------

// Template
<app-employee-resume
    [employeeId]="(employeeId$ | async)"
    (onUpload)="uploadResume($event)">
</app-employee-resume>

// Handler
uploadResume(resume: EmployeeResume) {    
    this.svc.upsertResume(resume)
}

// 'svc'
upsertResume(resume: EmployeeResume) {
    return this.http.put(`${this.apiUrl}/employee/resume`, resume);
}
333Matt
  • 1,124
  • 2
  • 19
  • 29
  • Maybe you need to JSON.stringify() the object,refer to this link:https://stackoverflow.com/a/38539880/11965297 – mj1313 May 25 '20 at 08:54

1 Answers1

3

You can use the ts FormData and a custom FileData object with any extra properties you want to store to the DB for this:

  onFileSelected(e: SelectEvent): void {
    this.uploadfile = e.files[0].rawFile;
  }

upload(): void {

const formData = new FormData();
const fileForSave = new FileData();

fileForSave.fileCategoryId = FileCategory.EmployeeResume;
fileForSave.description = this.f['description'].value;
fileForSave.employeeId = this.employeeId;

if (this.uploadfile) formData.append('file', this.uploadfile);
formData.append('fileForSave', JSON.stringify(fileForSave));

this.onUpload.emit(formData);
this.resetForm();
  }

  addFile(form: FormData): Observable<FileData> {
    return this.http.post<FileData>(`${this.apiUrl}/file/`, form);
  }

Then your API method will look something like this:

    [HttpPost]
    public async Task<IActionResult> AddFile(
        IFormFile file,
        [ModelBinder(BinderType = typeof(JsonModelBinder))] Contracts.Entities.File fileForSave)
    {
        // Check any file validations if you want

        /* Save the IFormFile file to disk */

        /* Save entity fileForSave File object to the DB */

        return Ok(newFile);
    }

And I'll even throw this in for ya:

public class JsonModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException(nameof(bindingContext));
        }

        // Check the value sent in
        var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (valueProviderResult != ValueProviderResult.None)
        {
            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);

            // Attempt to convert the input value
            var valueAsString = valueProviderResult.FirstValue;
            var result = Newtonsoft.Json.JsonConvert.DeserializeObject(valueAsString, bindingContext.ModelType);
            if (result != null)
            {
                bindingContext.Result = ModelBindingResult.Success(result);
                return Task.CompletedTask;
            }
        }

        return Task.CompletedTask;
    }
}
333Matt
  • 1,124
  • 2
  • 19
  • 29