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

2024-05-03

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

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--

问题解决了:

in 服务.ts它应该是

const headers = new HttpHeaders().append('内容处置', '多部分/表单数据');

代替

const headers = new HttpHeaders().append('内容类型', '多部分/表单数据');

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐