Send image with difference data type from angular 7 to Rest API in spring boot 2.0.5

Mohamad Alhamid :

I searched a lot in "stack overflow" and in other sites, no answer resolve my problem.

Angular html file:

<form (ngSubmit)="submit">
  <div>
    <input type="file" [(ngModel)]="data.image" name="image" (change)="onFileSelected($event)">
  </div>

  <div class="form">
    <mat-form-field>
      <input matInput [(ngModel)]="data.clientName" name="clientName">
    </mat-form-field>
  </div>
  //........ Other inputs fields here//
</form>  

Angular ts file:

public confirmAdd(): void {
  const payload: FormData = new FormData();
  payload.append('clientName', this.data.clientName);
  payload.append('dateOfBirth', this.data.dateOfBirth.toString());
  payload.append('mobileNumber', this.data.mobileNumber);
  payload.append('email', this.data.email);
  //...............other fields here ..........//
  payload.append('image', this.selectedFile); == > the image
}    

Angular Service ts file:

private httpHeaders = new HttpHeaders({
  'Content- Type': 'multipart/form-data'
});

this.http.post(this.urlEndTestImage, payload {
  headers: this.httpHeaders
}).subscribe(res => {
  console.log(res)
});   

spring boot Rest API:

@CrossOrigin(origins = {
  "http://localhost:4200"
})
@RestController
@RequestMapping("/apiHorsesClub")

public class ClienteRestController {

  @PostMapping("/upload")
  public String uploadMultipartFile(@RequestParam("model") String clientNew, @RequestParam(value = "image") MultipartFile image) {
    try {
      ObjectMapper mapper = new ObjectMapper();
      clientEntity client = mapper.readValue(clientNew, clientEntity.class);
      client.setImage(image.getBytes());
      clientService.save(client);
      return "successfully -> filename=" + image.getOriginalFilename();
    } catch (Exception e) {
      return "FAIL!file's size > 500KB";
    }
  }
}    

I am try to add more @RequestParam() and I am try @RequestPart() with the same name of fields but not work.

This image of postman request post:

it's work no problem and save the image with data to mySql

Mohamad Alhamid :

I solved my problem, the problem as you say @Sudarshana i don't match "model" in angular side, and after a lot search i found two method to send file with difference data:

  1. Send by (Data JSON, file)

    Angular html:

    <form   [formGroup]="profileForm" (ngSubmit)="onSubmit()">
     <input type="hidden" name="size" value="1000000">
     <div>
        <input type="file" (change)="onFileSelected($event)">
     </div>
     <div>
       <input type="text" formControlName="clientName" placeholder="client Name">
       <input type="text" formControlName="lastName" placeholder="Last Name">
       <input type="text" formControlName="age"  placeholder="Age">
       <button type="submit" name="upload">POST</button>
     </div>
    </form>
    

    Angular ts:

    profileForm = new FormGroup({
    clientName : new FormControl(''),
    lastName : new FormControl(''),
    age : new FormControl('')
    });
    
    selectedFile = null;
    public data:clientClass = new clientClass();
    
    onFileSelected(event) {
    this.selectedFile = event.target.files[0];
    console.log(this.selectedFile);
    }
    
    onSubmit() {
    let object = this.profileForm.value;
    const payload = new FormData();
    payload.append("addClient",JSON.stringify(object));
    payload.append("image", this.selectedFile, this.selectedFile.name);
    this.http.post(`http://localhost:8080/yourAPI/uploadTestEntity`,payload, { 
    responseType: 'text'}).subscribe(
      (object) => {
        this.profileForm.reset();
      });
    }
    

    App modules file:

    import { FormsModule, ReactiveFormsModule } from '@angular/forms';
    @NgModule({
    imports:[ BrowserModule, FormsModule,ReactiveFormsModule ]
    })
    

    Rest API:

    @PostMapping("/uploadTestEntity")
    public String uploadTestEntity(
    @RequestParam("addClient") String clientNameEntityNew,    
    @RequestParam(value = "image") MultipartFile image) {
      try {
          ObjectMapper mapper = new ObjectMapper();
          testEntity testEntity = mapper.readValue(clientNameEntityNew,testEntity.class);
          testEntity.setImage(image.getBytes());
          TestEntityService.save(testEntity);
        return "File uploaded successfully! -> filename = "+ image.getOriginalFilename();
          } catch (  Exception e) {
      return "FAIL! Maybe You had uploaded the file before or the file's size > 500KB";
    }    
    }
    

    2- send file and Data as params and receive as params in Rest API:

    Angular html:

    <form (ngSubmit)="onSubmit()">
     <input type="hidden" name="size" value="1000000">
     <div>
       <input type="file" name="image" (change)="onFileSelected($event)">
     </div>
    <div>
    <input id="textauthor" [(ngModel)]="clientName" name="clientName" placeholder="Name">
    <input id="textauthor" [(ngModel)]="lastName" name="lastName" placeholder="last 
    Name">
    <input id="textauthor" [(ngModel)]="age" name="age" placeholder="age">
    <button type="submit" name="upload">POST</button>
    </div>
    </form>
    

    Angular ts:

    clientName:string;
    lastName:string;
    age:string;
    resData: any;
    selectedFile = null;
    
    onFileSelected(event) {
    this.selectedFile = event.target.files[0];
    console.log(this.selectedFile);
    
    onSubmit() {
    const payload = new FormData();
    payload.append('clientName', this.clientName);
    payload.append('lastName', this.lastName);
    payload.append('age', this.age);
    payload.append('image', this.selectedFile, this.selectedFile.name);
    
    this.http.post(`http://localhost:8080/apiHorsesClub/uploadTestEntity`,
    payload).subscribe((data: any) => { this.resData = data;console.log(this.resData);
      });
    }
    

    Rest API:

    @PostMapping("/uploadTestEntity")
    public String uploadTestEntity(
             @RequestParam("clientName") String clientName ,
             @RequestParam("lastName") String lastName
             @RequestParam("age") String age
            ,@RequestParam(value = "image") MultipartFile image) {
      try {
    
          testEntity testEntity = new testEntity();
          testEntity.setImage(image.getBytes());
          testEntity.setClientName(clientName);
          testEntity.setLastName(lastName);
          testEntity.setAge(age);
        return "File uploaded successfully! -> filename = "+ image.getOriginalFilename();
    } catch (  Exception e) {
      return "FAIL! Maybe You had uploaded the file before or the file's size > 500KB";
    }    
    }
    

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=146366&siteId=1