使用 Asp.Net Core Web API 文件上传的文件始终为空

File upload using Asp.Net Core Web API file is always null

我正在使用 Angular 2 和 ASP.NET 核心 Web API 来实现文件上传来处理请求。

我的 html 代码如下:

<input #fileInput type="file"/>
<button (click)="addFile()">Add</button>

和angular2代码

addFile(): void {
    let fi = this.fileInput.nativeElement;
    if (fi.files && fi.files[0]) {
        let fileToUpload = fi.files[0];
        this.documentService
            .uploadFile(fileToUpload)
            .subscribe(res => {
                console.log(res);
        });
    }
}

服务看起来像

public uploadFile(file: any): Observable<any> {
    let input = new FormData();
    input.append("file", file, file.name);
    let headers = new Headers();
    headers.append('Content-Type', 'multipart/form-data');
    let options = new RequestOptions({ headers: headers });
    return this.http.post(`/api/document/Upload`, input, options);
}

和控制器代码

[HttpPost]
public async Task Upload(IFormFile file)
{
    if (file == null) throw new Exception("File is null");
    if (file.Length == 0) throw new Exception("File is empty");

    using (Stream stream = file.OpenReadStream())
    {
        using (var binaryReader = new BinaryReader(stream))
        {
            var fileContent = binaryReader.ReadBytes((int)file.Length);
            //await this.UploadFile(file.ContentDisposition);
        }
    }
}

我的 RequestHeader 看起来像

POST /shell/api/document/Upload HTTP/1.1
Host: localhost:10050
Connection: keep-alive
Content-Length: 2
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJDb3JyZWxhdGlvbklkIjoiZDZlNzE0OTUtZTM2MS00YTkxLWExNWUtNTc5ODY5NjhjNDkxIiwiVXNlcklkIjoiMSIsIlVzZXJOYW1lIjoiWjk5OTkiLCJXb3Jrc3BhY2UiOiJRc3lzVFRAU09BVEVNUCIsIk1hbmRhbnRJZCI6IjUwMDEiLCJDb3N0Q2VudGVySWQiOiIxMDAxIiwiTGFuZ3VhZ2VDb2RlIjoiMSIsIkxhbmd1YWdlU3RyaW5nIjoiZGUtREUiLCJTdGF0aW9uSWQiOiI1NTAwMSIsIk5hbWUiOiJJQlMtU0VSVklDRSIsImlzcyI6InNlbGYiLCJhdWQiOiJodHRwOi8vd3d3LmV4YW1wbGUuY29tIiwiZXhwIjoxNDk1Mzc4Nzg4LCJuYmYiOjE0OTUzNzUxODh9.5ZP7YkEJ2GcWX9ce-kLaWJ79P4d2iCgePKLqMaCe-4A
Origin: http://localhost:10050
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Content-Type: multipart/form-data
Accept: application/json, text/plain, */*
Referer: http://localhost:10050/fmea/1064001/content
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8

我面临的问题是控制器中的文件始终为空。

请有人帮我解决这个问题。

提前致谢。

您不需要将 'multipart/form-data' 与 FormData

一起使用

在 Angular 2 个分量中:

<input type="file" class="form-control" name="documents" (change)="onFileChange($event)" />

onFileChange(event: any) {
    let fi = event.srcElement;
    if (fi.files && fi.files[0]) {
        let fileToUpload = fi.files[0];

        let formData:FormData = new FormData();
         formData.append(fileToUpload.name, fileToUpload);

        let headers = new Headers();
        headers.append('Accept', 'application/json');
        // DON'T SET THE Content-Type to multipart/form-data, You'll get the Missing content-type boundary error
        let options = new RequestOptions({ headers: headers });

        this.http.post(this.baseUrl + "upload/", formData, options)
                 .subscribe(r => console.log(r));
    }
}

API 一侧

[HttpPost("upload")]
public async Task<IActionResult> Upload()
{
    var files = Request.Form.Files;

    foreach (var file in files)
    {
       // to do save
    }

    return Ok();
}

dotnet core 的另一种方式,您可以使用 IFormFile 接口,设置默认 headers:

Angular 2

 let formData = new FormData();
 formData.append("file", yourUploadFile);

 this.http.post("your_api_path", formData).subscribe(r => console.log(r));

Dotnet 核心

 [HttpPost]
 [Route("/your_api_path")]
 public async Task<IActionResult> Upload(IFormFile file) {
     //...next awaiters...    
}

如果要发送多个文件,可以使用ICollection<IFormFile>作为上传参数。

要发送多个属性,您可以使用自定义模型 object 并且 IFormFile 将是其中一个属性。

希望对您有所帮助!

更新: 经过 ASP.NET 核心团队的一些澄清后,它与 Startup class 中的兼容开关有关。如果你这样设置:

services
    .AddMvc()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

那么如果您也从文件参数中删除 [FromForm] 属性就没问题了。

旧Post: 我 运行 与最新的 ASP.NET Core WebApi(2.1.2 在这个 post 时)遇到了类似的问题,我只能在计算器溢出一个小时后偶然解决,研究和大量的试验和错误。我正在 post 从 Angular 6 应用程序中读取文件,如下所示:

const formData: FormData = new FormData();
formData.append('file', file, file.name);

const req = new HttpRequest('POST', 'upload-url', formData, {
    reportProgress: true
});

this.http.request(req).subscribe(...) // omitted the rest

问题是,即使将 [FromForm] 放在前面,IFormFile file 操作方法参数始终是 null[FromForm] 是必需的,因为 api 控制器行为在 ASP.NET Core 2.1 中发生了变化,其中 [FromBody] 成为 api 控制器的默认值。 st运行gely,还是不行,值还是null.

我最终通过使用属性显式声明表单内容参数的名称解决了这个问题,如下所示:

public async Task<IActionResult> UploadLogo([FromForm(Name = "file")] IFormFile file)        
{
     ...
}

现在文件上传已正确绑定到控制器参数。我希望这对以后的人有帮助,因为它几乎让我失去了理智 :D

核心 3.1

[HttpPost("upload-bulk-excel"), DisableRequestSizeLimit]
public IActionResult Upload()
{
  try
  {
    var file = Request.Form.Files[0];

Angular 8

uploadExcelFile() {
  const formData = new FormData();
  formData.append('file', this.fileToUpload, this.fileToUpload.name);

  this._httpClient.post(`${environment.apiUrl}/upload/upload-bulk-excel`, formData, {reportProgress: true, observe: 'events'})
    .subscribe(event => {
      if (event.type === HttpEventType.UploadProgress)
        this.uploadProgress = Math.round(100 * event.loaded / event.total);
      else if (event.type === HttpEventType.Response) {
        this.uploadMessage = 'Upload success.';
      alert('File uploaded successfully');
    }
  });

}