1

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?

2 Answers 2

4

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 to Angular 2 - File Upload using Web API

hope this help

Sign up to request clarification or add additional context in comments.

2 Comments

God bless your soul, for saving me from this monstrosity I got myself into.
Anytime dude :)
2

Step1: Ng2/4 Html-

 <input type="file" name="ProfilePhoto" id="ProfilePhoto" /> 

Step2: Ng2/4 Component-

import { ElementRef} from '@angular/core';
let files=this.elem.nativeElement.querySelector('#ProfilePhoto').files;
      let formData:FormData=new FormData();

      let file=files[0];
      formData.append('ProfilePhoto',file,file.name);         
      this.systemUserService.uploadSystemUserProfilePhoto(this.loginResponse.token,formData).subscribe(data => {  
      }); 

on service to be added below--- Note: here i used token based athentication, you can use normal http post.

uploadSystemUserProfilePhoto(token:string,formData: FormData): Observable<GlobalBaseResponse> {
            let options=this.getFileUploadHeader(token);                              
           return this.http.post(`${this.globalConstant.baseApiUrl}/account/uploadSystemUserProfilePhoto`, formData, options)
                   .map((response: Response) => {
                           this.globalBaseResponse = response.json();
                           return this.globalBaseResponse;
                   });
   }

           private getFileUploadHeader(token:string):RequestOptions{
            let headers = new Headers({ 
                    'Data-Type': 'json',
                    // 'Content-Type': false,
                    // 'Process-Data':false,
                    'Authorization':'Bearer '+token 
            });
            let options = new RequestOptions({ headers: headers });
            return  options;
    }

Step3: on Asp.net web api project api controller method-

    [HttpPost]
    [Route("uploadsystemuserprofilephoto")]       
    public IHttpActionResult UploadSystemUserProfilePhoto()
    {
        var response = new ResponseModel();

        var httpResponseMessage = 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($"~/webshared/user/{postedFile.FileName}");
                postedFile.SaveAs(filePath);
            }
        }           

        response.IsSuccess = true;
        response.Message = "Success, User profile photo updated!";
        return Ok(response);            
    }

I think this will helpful for you. Thanks

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.