-1

I want to upload a file on form submit, but its not posting on web API.

And save file in a local physical path using Web API.

Here I am trying to send file using FormData and trying to access the same in api call using HttpPostedFileBase but its posting on given url(no error).

Html :

<form [formGroup]="employeeForm" (ngSubmit)="save()" #formDir="ngForm" novalidate style="position:relative;" enctype="multipart/form-data">
  <div>
 <input class="form-control" type="text" formControlName="Name">
        <input type="file" id="FileUploader" (change)="onFileChange($event)" #fileInput accept=".pdf,.doc,.docx,.png">
        <button type="button" class="btn btn-sm btn-default" (click)="clearFile()">clear file</button>
      </div>
</form>

Component :

myFiles: string[] = [];
  form: FormGroup;
  loading: boolean = false;
  @ViewChild('fileInput') fileInput: ElementRef;

onFileChange(e) {        
  for (var i = 0; i < e.target.files.length; i++) {
    this.myFiles.push(e.target.files[i]);
   } 
  }
save() {
   const frmData = new FormData();
   let fileBrowser = this.fileInput.nativeElement;
   frmData.append("myFile", fileBrowser.files[0]);

      this._employeeService.saveEmployee(this.employeeForm.value, frmData)
        .subscribe((data) => {
          this._router.navigate(['/fetch-employee']);
        }, error => this.errorMessage = error)
    }

Service :

saveEmployee(employee, myFile): Observable<any> {
   return this._http.post(this.myAppUrl + 'api/Employee/Create', { employee: employee, myFile: myFile }, {
  headers: {
    'Content-Type': undefined,
    'Accept': 'application/json'
  }
 });
 }

Web API :

  public int Create([FromBody] TblEmployee employee, HttpPostedFileBase myFile)
            {
             //code    
            }
     public partial class TblEmployee
        {
            public int EmployeeId { get; set; }
            public string Name { get; set; }              
        }
Sunil Kumar
  • 909
  • 2
  • 17
  • 31

2 Answers2

1

Do not add Content-Type header. Let the browser detect the Content-Type and add by itself.

So comment out it in your code

saveEmployee(employee, myFile): Observable<any> {
   return this._http.post(this.myAppUrl + 'api/Employee/Create', { employee: employee, myFile: myFile }, {
    headers: {
    //'Content-Type': undefined,
    'Accept': 'application/json'
    }
  });
}
Amit Chigadani
  • 28,482
  • 13
  • 80
  • 98
  • Now, its returing POST http://localhost:35257/api/Employee/Create 500 (Internal Server Error).. – Sunil Kumar Jun 27 '18 at 13:30
  • What was the response returned earlier? – Amit Chigadani Jun 27 '18 at 13:30
  • i also tried these 2 but none of them is working for me, my api is on a different project bdw, https://stackoverflow.com/questions/51021454/angular-unable-to-upload-file-using-web-api and https://stackoverflow.com/questions/51016370/how-to-upload-a-file-on-form-submit-using-web-api-and-angular – Sunil Kumar Jun 27 '18 at 13:33
  • Seems like an issue with your api. Did you try testing from the postman or any other tools? – Amit Chigadani Jun 27 '18 at 13:35
  • One Advise : Before asking any question make sure that you research properly and let us know what is working and what is not. If you are not sure yourself, it is difficult to solve. – Amit Chigadani Jun 27 '18 at 13:58
  • i was not aware of how to post from postman with a file, thats why i didn't check yet.. – Sunil Kumar Jun 28 '18 at 04:42
0

You should put all your data insite FormData

const frmData = new FormData();
let fileBrowser = this.fileInput.nativeElement;
frmData.append("myFile", fileBrowser.files[0]);
frmData.append("employee", employee);

And the in API you should use IFormFile

public IActionResult Create(string employee, IFormFile myFile)

Update https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-2.1

public class TblEmployee 
{
    // your employee info

    public IFormFile MyFile{ get; set; }
}
public async Task<IActionResult> Register(RegisterViewModel model)
Dinh Duong
  • 297
  • 2
  • 10