title: How to Pass Data from Angular 10 form to Spring Boot Rest API that includes both Strings and Files/Images?
body: <p>I am getting the following error in Eclipse Console when trying to communicate between Angular 10 and Spring-Boot rest Api.</p>
  <pre><code>2020-10-06 23:44:12.261  WARN 33762 --- [nio-8090-exec-5] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `java.lang.String` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.lang.String` out of START_OBJECT token
   at [Source: (PushbackInputStream); line: 1, column: 535] (through reference chain: com.P.models.PModels[&quot;pProfilePic&quot;])]
  </code></pre>
  <p>This is part of my Angular Form</p>
  <pre><code>&lt;form class=&quot;&quot; action=&quot;&quot; method=&quot;POST&quot; enctype = &quot;multipart/form-data&quot; role=&quot;form&quot; [formGroup]=&quot;form&quot; (ngSubmit)=&quot;onSubmit()&quot;&gt;
  
                    &lt;input id=&quot;name&quot; class=&quot;form-control&quot; type=&quot;text&quot; placeholder=&quot;Your Name&quot; formControlName=&quot;pName&quot;
                      class=&quot;form-control&quot; [ngClass]=&quot;{ 'is-invalid': submitted &amp;&amp; f.pName.errors }&quot;&gt;
                    &lt;div *ngIf=&quot;submitted || f.pName.invalid &amp;&amp; (f.pName.dirty || f.pName.touched)&quot;
                      class=&quot;alert alert-danger&quot;&gt;
                      &lt;div *ngIf=&quot;f.pName.errors?.required&quot;&gt;Name is required&lt;/div&gt;
                    &lt;/div&gt;
  
  &lt;div class=&quot;form-group row mb-4&quot;&gt;
              &lt;label for=&quot;uploadPhoto&quot; class=&quot;col-md-3 col-form-label&quot;&gt;Upload Photo &lt;/label&gt;
              &lt;div class=&quot;col-md-8&quot;&gt;
                &lt;input type=&quot;text&quot; class=&quot;form-control mb-2 transparent-disabled&quot; id=&quot;uploadPhoto&quot;
                  placeholder=&quot;JPEG size 200kb max&quot; [value]=&quot;filePhotoInfo&quot; disabled&gt;
                 &lt;div *ngIf=&quot;submitted || f.pProfilePhoto.invalid &amp;&amp; (f.pProfilePhoto.dirty || f.pProfilePhoto.touched)&quot;
                  class=&quot;alert alert-danger&quot;&gt;
                  &lt;div *ngIf=&quot;f.pProfilePhoto.errors?.required&quot;&gt; Upload JPEG file and it should not exceed 200kb&lt;/div&gt;
                &lt;/div&gt; 
                &lt;button type=&quot;button&quot; class=&quot;btn btn-outline-primary btn-upload&quot;&gt;&lt;i class=&quot;fas fa fa-cloud-upload&quot;&gt;&lt;/i&gt;
                  Upload File
  
                  &lt;input
                        formControlName=&quot;pProfilePhoto&quot; 
                        type=&quot;file&quot; 
                        (change)=&quot;onPhotoSelect($event)&quot;
                        class=&quot;form-control&quot; 
                        &gt;
                &lt;/button&gt;
              &lt;/div&gt;
            &lt;/div&gt;
  </code></pre>
  <p>This is part of my Registration ts file</p>
  <pre><code>import { Component, OnInit } from '@angular/core';
  import { NgbModalConfig, NgbModal } from '@ng-bootstrap/ng-bootstrap';
  import { FormBuilder, FormControl, Validators } from '@angular/forms';
  import { ActivatedRoute, Router } from '@angular/router';
  import { ValidationService } from 'src/app/Services/validation.service';
  import { PRegistrationService } from 'src/app/Services/P-Services/p-registration.service';
  @Component({
    selector: 'app-p-registration',
    templateUrl: './p-registration.component.html',
    styleUrls: ['./p-registration.component.css', '../../../app.component.css'],
    providers: [NgbModalConfig, NgbModal]
  
  })
  
  
  export class PRegistrationComponent implements OnInit {
    checkbox1 = false;
    form: any;
    loading = false;
    submitted = false;
    public fileData = {};
     constructor(
      private PRegistrationService : PRegistrationService,
      config: NgbModalConfig,
      private modalService: NgbModal,
      private formBuilder: FormBuilder,
      private route: ActivatedRoute,
      private router: Router,
      private customValidator: ValidationService,
      ) {
      // customize default values of modals used by this component tree
      config.backdrop = 'static';
      config.keyboard = false;
  }
  
  ngOnInit() {
    this.form = this.formBuilder.group({
      pName: ['', Validators.required],
        pProfilePhoto: ['', Validators.required],
        pProfilePic: new FormControl(''),
    });
  }
  // convenience getter for easy access to form fields
    get f() { return this.form.controls; }
  
    // tslint:disable-next-line: typedef
    onSubmit() {
      this.submitted = true;
      if (this.form.valid) {
        const formData = new FormData();
        formData.append('pProfilePic', this.form.get('pProfilePic').value);
        this.PRegistrationService.pRegistration(this.form.value)
          .subscribe(result =&gt; {
            this.router.navigate(['PRegistration']);
          }, (err) =&gt; {
            console.log(err);
          });
      }
    }
    // tslint:disable-next-line: typedef
    reset(){
      this.form.reset();
    }
    // tslint:disable-next-line: typedef
    open(content) {
      this.modalService.open(content, { centered: true });
    }
  
  
    filePhotoInfo: string ='';
  
    onPhotoSelect(event) {
    
      if (event.target.files.length &gt; 0) {
        const pProfilePhoto = event.target.files[0];
        console.log('this is ')
        console.log(pProfilePhoto);
        this.filePhotoInfo = `${pProfilePhoto.name}`;
        this.form.patchValue({
          pProfilePic: pProfilePhoto
        });
      }
    }
  }
  </code></pre>
  <p>This is part of my service ts file</p>
  <pre><code>export class PRegistration {
      public pId: number;
      public pName: string;
      public pProfilePic: File;
  
      constructor(    
          pId: number,
          pName: string,
          pProfilePic: File) 
          
          {
          this.pId = pId;
          this.pName = pName;
          this.pProfilePic = pProfilePic;
      }    
  
  }
  </code></pre>
  <p>This is part of my Service file</p>
  <pre><code>import { Injectable } from '@angular/core';
  import { Observable } from 'rxjs';
  import {HttpClient,HttpHeaders} from &quot;@angular/common/http&quot;;
  import { environment } from 'src/environments/environment';
  import { PRegistration } from 'src/app/Services/P-Services/p-registration';
  
  @Injectable({
    providedIn: 'root'
  })
  export class PRegistrationService {
    constructor(private http: HttpClient) { }
    httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json',
      })
    }
    pRegistration(p):Observable&lt;any&gt;{
  
      return this.http.post&lt;PRegistration&gt;(environment.api_url+&quot;save_user&quot;,p,this.httpOptions)
    
    }
  }
  </code></pre>
  <p>This is part of my model</p>
  <pre><code>@Entity
  @Table(name = &quot;prepository&quot;)
  public class PModels {
  
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private int pId;
  @Column(nullable = false)
  private String pName;
  private String pProfilePic;
  
  // Constructor, getter and setter, toString
  </code></pre>
  <p>This is part of my service</p>
  <pre><code>public void saveUser(String pName,MultipartFile pProfilePic) {
      try {
          String pProfilePic_file = pProfilePic.getOriginalFilename();
          
          InputStream pProfilePic_is = pProfilePic.getInputStream();
          
          String pProfilePic_ts = String.valueOf(System.currentTimeMillis());
          try { Thread.sleep(1);} catch (InterruptedException e) { e.printStackTrace();}
          
          String rand = UUID.randomUUID().toString();
          
          String pProfilePic_name = pProfilePic_ts+rand+pProfilePic_file;
          
      PModels p = new PModels();
      
      p.setpName(pName);
      p.setpProfilePic(pProfilePic_name);
  
      pDao.save(p);
      
      String folder = &quot;//Users//Desktop//p//&quot;;
      Path path = Paths.get(folder);
      if (!Files.exists(path)) {
          try {
              Files.createDirectory(path);
  
              }
          catch (IOException e) {
              e.printStackTrace();
              }
          System.out.println(&quot;Directory created&quot;);
          }
      else {
          System.out.println(&quot;Directory already exists&quot;);
          }
      folder = folder + p.getPId() + &quot;//&quot;;
      Path path1 = Paths.get(folder);
      if (!Files.exists(path1)) {
          try {
              Files.createDirectory(path1);
          }
          catch (IOException e) {
              e.printStackTrace();
              }
          System.out.println(&quot;Directory created&quot;);
          }
      else {
          System.out.println(&quot;Directory already exists&quot;);
          }
        Files.copy(pProfilePic_is,Paths.get(folder+pProfilePic_name),StandardCopyOption.REPLACE_EXISTING);
    
    
  } catch (IOException e) {
      e.printStackTrace();
  }
      
  }
  </code></pre>
  <p>This is part of my controller</p>
  <pre><code>@PostMapping(&quot;/save_user&quot;)
       
      
        public void saveUser(@RequestBody PModels pModels) {
        this.pInfo.saveUser(pModels);
        
        System.out.println(pModels.getpName()); // Just for checking
  </code></pre>