Search code examples
c#angularfile.net-coreiformfile

posting File in angular


I'm trying to post an uploaded file in angular 5 to c# controller. When I debug my applicaion and post and hit the controller the [FromBody] IFormFile file is always null

Is their a specific {responseType} I need to pass from my angular service?

Angular Service

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
}

Why is my Post Body always null?


Solution

  • You can't just pass a file in the body of a post request in Angular. You have to send it as 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);
    }
    

    And in your controller, get the file like this

    [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
    }