I am trying to upload file using Angular 2 with web API but I am not getting file on the server.
My Controller method is
[HttpPost]
[Route("add")]
public IHttpActionResult Add(CourseDto course)
{
try
{
return Ok("");
//course.CompanyId = User.Identity.GetUserId<int>();
//var result = _courseService.Add(course);
//return Ok(result.Message);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
My CourseDto is
public class CourseDto
{
public int Id { get; set; }
public HttpPostedFileBase CourseFile { get; set; }
}
My Html file is
<form class="form-horizontal" #courseForm="ngForm" (ngSubmit)="onSubmit()" enctype="multipart/form-data">
<div class="form-group">
<label class="control-label col-sm-4">Browse Course:</label>
<div class="col-sm-8">
<input type="file" name="file" (change)="onChange($event)"/>
</div>
</div>
<footer>
<div class="row">
<div class="col-md-12 col-lg-12 col-xs-12">
<div class="pull-right">
<button type="submit" class="btn btn-primary" [disabled]="!courseForm.form.valid">Add</button>
<button type="button" class="btn btn-default" (click)="close()">Close</button>
</div>
</div>
</div>
</footer>
</form>
Course Model For typescript is
export class Course {
constructor(
public courseFile?:any ,
public id?: number
) {
}
}
My Angular 2 Component method is method is
onSubmit() {
this.httpService.post("course/add", this.courseModel)
.subscribe(result => {
this.loggerService.notify(this, "Courses added successfully", Toast[Toast.success]);
this.httpService.onUpdateModel();
this.refreshModel();
}, error => {
console.log(error);
});
}
onChange(event) {
this.courseModel.courseFile =event.target.files[0];
}
Angular 2 Http Post Method is
post(url: string, data: any) {
url = `${appConfig.apiUrl}${url}`;
this.progressBarService.RequestStarted();
return this.http.post(url, data)
.finally(() => this.progressBarService.RequestFinished())
.map((result: Response) => result.json())
.catch(this.handleError);
}
I successfully received the model in my Web API controller but without File. How to send the file to the web api controller model?