How to Upload File from Angular to ASP.NET Core Web API

my BlogController looks like this:

[HttpPost]

public async Task<ActionResult<Blog>> PostBlog([FromForm]PostBlogModel blogModel)

It seems that you’d like to pass data using form-data, to achieve it, you can refer to the following code sample.

.component.html

<form [formGroup]="newBlogForm" (ngSubmit)="onSubmit(newBlogForm.value)">

  <div>
      <label for="Name">
          Blog Name
      </label>
      <input type="text" formControlName="Name">
  </div>

  <div>
      <label for="TileImage">
          Tile Image
      </label>
      <input type="file" formControlName="TileImage" (change)="onSelectFile($event)" >
  </div>

  <button type="submit">Create Blog</button>

</form>

.component.ts

selectedFile: File = null;
private newBlogForm: FormGroup;
constructor(private http: HttpClient) { }

ngOnInit() {
  this.newBlogForm = new FormGroup({
    Name: new FormControl(null),
    TileImage: new FormControl(null)
  });
}

onSelectFile(fileInput: any) {
  this.selectedFile = <File>fileInput.target.files[0];
}

onSubmit(data) {
  
  const formData = new FormData();
  formData.append('Name', data.Name);
  formData.append('TileImage', this.selectedFile);

  this.http.post('your_url_here', formData)
  .subscribe(res => {

    alert('Uploaded!!');
  });

  this.newBlogForm.reset();
}

Test Result

enter image description here

Leave a Comment