【发布时间】:2022-12-24 15:30:02
【问题描述】:
我正在尝试使用 Angular 和 .Net 上传文件,下面是我使用过的代码。
我收到错误消息,例如需要文件字段,但我正在上传文件,但仍然收到错误消息。
errors: {file: ["The file field is required."]}
file: ["The file field is required."]
status: 400
title: "One or more validation errors occurred."
type: "https://tools.ietf.org/html/rfc7231#section-6.5.1"
下面是.Net 端代码。
[HttpPost("weeklyproductionreports/uploadfilesnew")]
public async Task<IActionResult> UploadWeeklyProductionReportsFiles([FromForm] IFormFile file) =>
Ok(await _companyService.UploadWeeklyProductionReportsFiles(file));
下面是 Html 代码。
<div class="myfilebrowser">
<input type="file" #UploadFileInput id="fileUpload" (change)="fileChangeEvent($event)" name="fileUpload"
multiple="multiple"
accept="application/pdf,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />
</div>
下面是ts文件代码。
fileChangeEvent(fileInput: any) {
if (fileInput.target.files && fileInput.target.files[0]) {
this.file = fileInput.target.files[0];
}
}
upload() {
this.isSubmitting = true;
let formData = new FormData();
formData.append('file', this.file, this.file.name);
this.apiService.uploadWeeklyProductionReportFile(formData).subscribe(
(data) => {
this.isSubmitting = false;
if (data.statusCode == 200) {
console.log(data);
this.uploadedFileUrl = data.data[0];
this.snackBar.open('File uploaded!', 'Ok', {
duration: 2000,
});
this.isShowFileUpload = true;
} else {
this.snackBar.open('File Upload Error: Please Try again', 'Ok', {
duration: 2000,
});
}
},
(error) => {
this.isSubmitting = false;
console.log(error);
this.snackBar.open('File Upload Error: Please Try again', 'Ok', {
duration: 2000,
});
}
);
console.log('Upload works');
}
下面是 API 调用代码。
uploadWeeklyProductionReportFile(body: FormData): Observable<any> {
const url = this.baseURL + '/company/weeklyproductionreports/uploadfilesnew';
return this.http.post<any>(url, body, { headers: { 'content-type': 'multipart/form-data' } });
}
【问题讨论】:
-
我推断问题发生在撰写表单时,您可以在向您的 API 发送请求时在 F12 中查看表单数据吗?如果表单的属性名称为
file,对应的值为文件 steam?顺便说一下,我认为有很多示例可以将文件从 Angular 客户端上传到 asp.net core api,例如this。你能看看吗?
标签: c# angular asp.net-core asp.net-web-api asp.net-core-webapi