【问题标题】:File uploading using .net angular error coming like file is required even file is uploaded使用 .net 角度错误上传文件需要即使文件已上传
【发布时间】: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


【解决方案1】:

所以我首先采用您编写的 upload() 方法,并向其添加一个输入参数,

upload(files: Array<any>)

以及您附加表单数据的位置我会执行以下操作:

formData.append(files[0].name, files[0])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-30
    • 2014-11-16
    • 2022-01-05
    • 2015-03-12
    • 2018-06-04
    • 2015-03-24
    • 2016-11-09
    • 2017-02-21
    相关资源
    最近更新 更多