Angular 2 With Web API File Upload -
i trying upload file using angular 2 web api not getting file on 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 typescript
export class course { constructor( public coursefile?:any , public id?: number ) { } }
my angular 2 component method 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
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 received model in web api controller without file. how send file web api controller model?
try this
httpresponsemessage response = new httpresponsemessage(); var httprequest = httpcontext.current.request; if (httprequest.files.count > 0) { foreach (string file in httprequest.files) { var postedfile = httprequest.files[file]; var filepath = httpcontext.current.server.mappath("~/uploadfile/" + postedfile.filename); postedfile.saveas(filepath); } }
thanks angular 2 - file upload using web api
hope help
Comments
Post a Comment