asp.net mvc - 使用 Angular/TypeScript 从 kendo-upload 向 .NET 应用程序发送文件数据
我有一个证书文件,需要通过 Kendo 上传或文件选择上传,读取文件中的数据并提交到 MVC 应用程序的 API。我尝试了使用文件读取器的不同方法,但似乎无法正常工作。最终,无论是来自 vm 还是 dto,我都需要将证书转换为 byte[] 以保存到数据库。
html :
<div *ngIf="!certificateExists; else addCertificateTemplate">
<div class="form-row">
<div style="padding-bottom: 10px">
<strong>Certificate</strong>
</div>
<kendo-formfield>
<kendo-fileselect
formControlName="certificate"
#fileSelect="kendoFileSelect"
[multiple]="false"
[restrictions]="fileRestrictions"
[disabled]="!isEditable"
(ngModelChange)="onChangeFile($event)">
<kendo-upload-messages
select="Select a file to upload"
dropFilesHere="Drop file here to upload">
</kendo-upload-messages>
</kendo-fileselect>
<kendo-formerror
*ngIf="
form.controls?.file?.errors?.required &&
fileSelect.fileList.files.length === 0">
Select a file to upload
</kendo-formerror>
</kendo-formfield>
</div>
</div>
ts 组件:
handleFormSubmit(): void {
const formValue = this.form?.getRawValue();
if (this.form?.valid) {
const data = this.form?.value as SomeDto;
const payload = this.createSubmitPayload(data, formValue);
this.service
.save(payload, true)
.pipe(
tap((r) => {
this.onSave(r.id);
})
)
.subscribe();
} else {
openExpansionPanels(this.expansionPanels);
}
}
onChangeFile(files: any): void {
// I'm not sure what to do here
const file = files[0];
console.log(file);
}
ts 服务:
save(
data: SomeDto
): Observable<SomeDto> {
return this.httpClient
.post<SomeDto>(
`${API_BASE}/someBaseRoute/save`,
data
)
.pipe(
this.pageLoaderService.wrapWithLoader(
'save'
)
);
}
虚拟机:
public class SomeVm
{
public type Property1 { get; set; }
public byte[] Certificate { get; set; }
public type Property3 { get; set; }
}
控制器
[HttpPost]
[Route("save")]
public HttpResponseMessage Save(HttpRequestMessage request, [FromBody] SomeVm vm)
{
return GetHttpResponse(
request, () =>
{
var someDto = new SomeDto
{
Property1 = vm.Property1,
Certificate = vm.Certificate,
Property3 = vm.Property3
};
someDto = _httpClient.Post<SomeDto, SomeDto>("apiRoute/update", someDto).Result;
return request.CreateResponse(HttpStatusCode.OK, someDto);
}
);
}
我在这里提供了很多代码上下文只是为了给出完整的情况。然而,我认为可能只是我在 TypeScript 组件中读取文件数据的某个概念上有所遗漏。