pjo*_*net 4 asp.net-core asp.net-core-webapi angular
当查看其他答案和一些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--
问题解决了:
在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在评论中指出的那样,只要参数名称与表单数据中的名称匹配,它就是基于约定的。
| 归档时间: | 
 | 
| 查看次数: | 2225 次 | 
| 最近记录: |