-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; }              
        }
1
  • What is the response received in network tab? Commented Jun 27, 2018 at 13:21

2 Answers 2

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'
    }
  });
}
Sign up to request clarification or add additional context in comments.

6 Comments

Now, its returing POST localhost:35257/api/Employee/Create 500 (Internal Server Error)..
What was the response returned earlier?
i also tried these 2 but none of them is working for me, my api is on a different project bdw, stackoverflow.com/questions/51021454/… and stackoverflow.com/questions/51016370/…
Seems like an issue with your api. Did you try testing from the postman or any other tools?
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.
|
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)

4 Comments

how to use this IFormFile ? or it should be formcollection?
You can one by one append data from all properties in employee object to FormData and then send to server
Failed to load resource: the server responded with a status of 415 (Unsupported Media Type)
its really difficult to upload a file on angular with other form properties????????

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.