gpt4 book ai didi

angular - .net 核心 2.2 和 Angular 7 : IFormFile in file upload controller is always null

转载 作者:太空狗 更新时间:2023-10-29 18:17:46 25 4
gpt4 key购买 nike

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

Api uris 等都是正确的,请求到达了正确的 Controller

Angular 片段:

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 - 从 View 中获取数据

@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 Controller 中,添加或删除作为参数前缀的 [FromForm(Name = "file")] 不会改变行为。无论有没有它,它都可以正常工作。正如雨果在评论中指出的那样,只要参数名称与表单数据中的名称匹配,它就是基于约定的。

关于angular - .net 核心 2.2 和 Angular 7 : IFormFile in file upload controller is always null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55008484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com