以角度发布文件

时间:2018-03-28 15:43:48

标签: c# angular file .net-core iformfile

我试图将上传的文件以角度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#Controller

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

为什么我的帖子正文始终为空?

1 个答案:

答案 0 :(得分:1)

你不能只在Angular中传递post请求正文中的文件。您必须将其作为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
}