angulartypescriptangular8ng-file-upload

How to upload image using angular 8


app.module.ts

 ngOnInit() {
this.userForm = this.fb.group({
  firstName : ['', Validators.required],
  gender : ['', Validators.required],
  maritalStatus : ['', Validators.required],
  lastName : ['', Validators.required],
  dob : ['', Validators.required],
  nationality : ['', Validators.required],
  pic : [''],
  streetAddress : ['', Validators.required],
  city : ['', Validators.required],
  postalCode : ['', Validators.required],
  phone : ['', Validators.required],
  state : ['', Validators.required],
  country : ['', Validators.required],
  email : ['', Validators.required],
  jobTitle : ['', Validators.required],
  dateOfJoining : ['', Validators.required],
  department : ['', Validators.required],
  employeeStatus : ['', Validators.required],
  kra : ['', Validators.required],
  assignedSupervisor : ['', Validators.required],
  assignedSubordinate : ['', Validators.required],
  workExperience : ['', Validators.required],
  skills : ['', Validators.required],
  education : ['', Validators.required],
  password : ['', Validators.required]
})
}

onSubmit() {
this.submitted = true;
this.userService.addUser(this.userForm.value).subscribe(
  res => {
    this.model = res
    console.log(res)
  },
  error => {
    this.error = error,
    console.log(error)
  }
)

app.component.html

<div class="col-lg-12 col-12 mt-2">
 <label for="pic">Profile Picture</label><br/>
 <input type="file" formControlname='pic' name='pic'/>
</div>

app.service.ts

addUser(formData: User) {
return this.http.post<User>(`${this.serverUrl}`, formData).pipe(
  catchError(this.handleError)
);

}

Eveything is working fine. I just want to know how to upload pic in angular 8. Pic is uploading in backend using node tested on postman. Can anyone help me how can i upload pic using angular, Please help me out


Solution

  • Before making the post request convert your formData into actual FormData like described here: https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData.

    Use

    addUser(formData: User) {
      const body = new FormData();
      for(const [key, value] of Object.entries(formData)){
         if(key === 'pic'){
            body.append(key, value)
         }
         body.append(key, `${value}`)
      }
      return this.http.post<User>(`${this.serverUrl}`, body).pipe(catchError(this.handleError);
    );
    

    Then your backend should recognize the file. Unfortunately FormData expects a string or a blob as the datatype for the value.

    Although it is stated:

    If the sent value is different than String or Blob it will be automatically converted to String: (...)

    my editor (vs code) tells me not to use a number, but convert it first.

    The solution is assuming that the datatypes of the other properties inside User are primitives.