【问题标题】:Can not send a file with Ajax using FormData in angular 7无法使用 Angular 7 中的 FormData 发送带有 Ajax 的文件
【发布时间】:2019-03-29 19:31:49
【问题描述】:

我正在使用 ASP.NET Core 作为后端,我正在尝试使用 ajax 在 Angular 7 中发送文件。 我创建了一个 FormData 类的对象,并使用 append 方法将文件添加到该对象中。 但我会在尝试顶部发布 api 时出错:

Error: {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":415,"statusText":"Unsupported Media Type","url":"https://localhost:44319/Api/TimeLinePost","ok":false,"name":"HttpErrorResponse","message":"Http failure response for https://localhost:44319/Api/TimeLinePost: 415 Unsupported Media Type","error":{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.13","title":"Unsupported Media Type","status":415,"traceId":"0HLLKF4AT3QD7:00000005"}}

这是我的角度代码:

export class StatusComponent {
  selectedImage: File = null;
  constructor(private http: HttpClient, @Inject('BASE_URL') private baseUrl: string) {

  }
  onImageSelected(event) {
    this.selectedImage = <File>event.target.files[0];
  }
  update() {
    const fd = new FormData();
    fd.append('image', this.selectedImage, this.selectedImage.name);
    this.http.post<boolean>(this.baseUrl + 'Api/TimeLinePost', fd).subscribe(
      result => {
      },
      error => {
        alert('Ops! Somthing went wrong!');
        console.log(`Error: ${JSON.stringify(error)}`)
      }
    )
  }
}

这是我的 api:

[HttpPost]
public bool Post(IFormFile image)
{ 
    return true;
}

【问题讨论】:

    标签: c# angular angular7 asp.net-core-2.2


    【解决方案1】:

    可以通过两种方式解决。

    1) 将[FromForm] 属性添加到操作参数(如this question 中所回答):

    [HttpPost]
    public bool Post([FromForm] IFormFile image)
    { 
        return true;
    }
    

    2) 在配置中添加SetCompatibilityVersion(CompatibilityVersion.Version_2_2)。它会自动解决绑定问题:

    public void ConfigureServices(IServiceCollection services)
    {
       services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-24
      • 2021-10-22
      • 2018-03-18
      • 1970-01-01
      • 2018-11-14
      • 2019-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多