3

我正在尝试将上传的 Angular 5 文件发布到 c# 控制器。当我调试我的应用程序并发布并点击控制器时,[FromBody] IFormFile 文件始终为空

他们是我需要从我的角度服务传递的特定 {responseType} 吗?

角服务

public async upload(file: File) {
  try {
    return await this.http.post(this.baseUrl + "api/Blogs/Upload", file).toPromise();
  catch (error) {
    console.log(JSON.stringify(error));
  }
}

C# 控制器

[HttpPost]
[Route("api/Blogs/Uplaod")]
public async Task<IActionResult> Upload([FromBody] IFormFile file) {
  // my save logic
}

为什么我的帖子正文总是为空?

4

1 回答 1

1

您不能只在 Angular 的发布请求正文中传递一个文件。您必须将其作为 formData 发送

uploadFile(file: File) {
  var formData: FormData = new FormData();
  formData.append('file', file, file.name);

  var headers = new HttpHeaders().set('Accept', 'application/json');
  var options = { headers: headers };

  const req = new HttpRequest('POST', this.baseUrl + "api/Blogs/Upload", formData, options);
  return this.http.request(req);
}

在您的控制器中,获取这样的文件

[HttpPost]
[Route("api/Blogs/Upload")]
public async Task<IActionResult> Upload() {
  var myFile = HttpContext.Current.Request.Files(0)
  // you can append more than 1 file in angular, but if you know its only ever 1 file, you can just get the `Files(0)` at that index of zero.
  // my save logic
}
于 2018-03-28T16:29:45.267 回答