.net core 2.2和Angular 7:文件上传控制器中的IFormFile始终为null

时间:2019-03-05 17:32:14

标签: angular asp.net-core asp.net-core-webapi

在查看其他答案和一些Google时,一切似乎都很好,但是我的控制器从未收到任何数据。

Api uris等是正确的,请求到达了正确的控制器

角度片段:

component.html-我的输入字段

<div class="input-group">
    <input type="file" #fileInput id="fileInput" (change)="stageFile()"
           accept="csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel">
    <div class="input-group-append">
        <button class="btn btn-primary" type="button" (click)="fileUpload()" [disabled]="!staged || uploading">
          <span *ngIf="!uploading,else loadAnim">Upload</span>
          <ng-template #loadAnim>Uploading...</ng-template>
        </button>
    </div>
</div>

component.ts-从视图获取数据

@ViewChild('fileInput') fileInput;
private file: File;
public uploading = false;
public staged = false;

constructor(private uploadService: UploadService) { }

public stageFile(): void {
    this.staged = true;
    this.file = this.fileInput.nativeElement.files[0];
    console.log(this.file)
}

public fileUpload():void {
    this.uploading = true;
    if (this.file != null)
      this.uploadService.upload(this.file).subscribe();
    this.staged = false;
    this.uploading = false;
}

services.ts-处理实际的ajax调用

private uploadURI = environment.dataServiceURI + '/upload';

constructor(private http: HttpClient) {}

public upload(file: File): Observable<object> {
// create multipart form for file
let formData: FormData = new FormData();
formData.append('file', file, file.name);

const headers = new HttpHeaders().append('Content-Type', 'mulipart/form-data');

// POST
return this.http
  .post(this.uploadURI, formData, {headers: headers})
  .pipe(map(response => response));
}

.net核心代码段

在这里IFormFile文件始终包含null,因此我的结果始终为500

[HttpPost("upload")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public IActionResult ParseData([FromForm(Name = "file")] IFormFile file)
{
    if (file == null)
       return StatusCode(500);
    (...)
    return Ok()
 }

请求有效载荷信息

通过浏览器网络

------WebKitFormBoundarycBigaNKzS4qNcTBg 
Content-Disposition: form-data; name="file"; filename="test_data_schema.xlsx" 
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

------WebKitFormBoundarycBigaNKzS4qNcTBg--

1 个答案:

答案 0 :(得分:1)

问题已解决:

service.ts 中应该是

  

const headers = new HttpHeaders()。append(' Content-Disposition ','multipart / form-data');

代替

  

const headers = new HttpHeaders()。append(' Content-Type ','multipart / form-data');

也在 .net控制器中,添加或删除 [FromForm(Name =“ file”)] 作为参数前缀不会改变行为。无论有没有它,它都能完美地工作。正如hugo在评论中指出的那样,只要参数名称与表单数据中的名称相匹配,它就是基于约定的。