您如何使用kendo-fileselect从有角度的应用程序上传到C#Web API?

问题描述 投票:0回答:1

我们正在我们的项目中实现针对角的剑道。我们有一个正在使用kendo-upload的现有项目,该项目会立即触发对服务器的调用,但是我无法在此页面上执行此操作。

Screenshot

该页面供员工上传简历。他们可能已有一份简历,并且需要先询问是否要替换它,并为他们提供一个用于输入描述的字段。因此,我认为我需要使用kendo-fileselect并可能触发一个对话框(确定要替换吗?),并在单击按钮时附带说明和员工ID。因此,我创建了一个携带这些数据的对象。

[当调用该API时,您可以看到该对象已填充:

Debugging Resume

但是当我尝试调用API方法时,出现错误:

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

Error Details

下面是相关代码。

服务器端:

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();
    }

客户端:

// 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);
}
angular file-upload kendo-ui asp.net-core-webapi
1个回答
0
投票

您可以将ts FormData和自定义FileData对象与您要为此存储到数据库的任何其他属性一起使用:

  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);
  }

然后您的API方法将如下所示:

    [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);
    }

而且我什至会把它扔给你:

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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.