Angular 11 不会将文件上传到 .NET 5

Angular 11 won't upload file to .NET 5

我无法从我的 Angular 11 应用程序中获取文件上传到我的 .NET 5 服务。如果我在控制器方法的第一行设置一个断点,它不会被命中。 angular 应用程序刚刚获得一个状态为 0 的 HttpErrorResponse。我能够 POST 对同一个控制器中的其他方法没有问题,所以我知道所有“设置”类型一切正常。

我在 Angular 端像这样上传:

postUploadLegacyData(files: File[]): Observable<string[]> {
    const formData = new FormData()
    files.forEach(x => formData.append('file', x, x.name))

    return this.http.post<string[]>('requests/import', formData)
}

然后在 .NET 方面我有这个:

[Route("[controller]"), Produces("application/json"), Authorize, ApiController]
public class RequestsController : ControllerBase
{
    [HttpPost("import")]
    [Consumes("multipart/form-data")]
    public IActionResult PostImportExistingRequests(IEnumerable<IFormFile> files)

已解决

我发现在服务器端应该是这样的:

public async Task<IActionResult> PostImportExistingRequestsAsync()
{
    var form = await Request.ReadFormAsync();
    var files = form.Files;

Angular: 为您的组件构建一个前端文件夹 angular ng g component upload --spec false


import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { HttpEventType, HttpClient } from '@angular/common/http';

@Component({
  selector: 'file-upload-toAspCore',
  templateUrl: './upload.component.html',
  styleUrls: ['./upload.component.css']
})
export class UploadComponent implements OnInit {
  public progress: progressPercentage;  // you can yse this to display progress in HTML
  public message: string;
  
  @Output() public onUploadFinished = new EventEmitter();    
  constructor(private http: HttpClient) { }

  ngOnInit() {}

  public uploadFile = (files) => {
    if (files.length === 0) {
      return;
    }

    let filesToUpload = <File>files[0];
    const formData = new FormData();
    formData.append('file', filesToUpload, filesToUpload.name);

    this.http.post('https://localhost:4200/api/uploaderAction', formData, 
    {reportProgress: true, observe: 'events'})
      .subscribe(event => {
      
        if (event.type === HttpEventType.UploadProgress)
          // helps display progress to user
          this.progress = Math.round(100 * event.loaded / event.total);
          
        else if (event.type === HttpEventType.Response) {
          this.message = 'Upload success.';
          this.onUploadFinished.emit(event.body);
        }
      });
  }
}

ASP 接收文件的动作

   [HttpPost, DisableRequestSizeLimit]
    public async Task<IActionResult> UploaderAction()
    {
        try
        {
            var formCollection = await Request.ReadFormAsync();
            var file = formCollection.Files.First();