Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 508
Mohamad Alhamid Avatar asked Nov 19 '25 23:11

Mohamad Alhamid


1 Answers

You have missed , in your Service.

   private httpHeaders = new HttpHeaders({'Content- Type':'multipart/form-data'});
       this.http.post(this.urlEndTestImage, payload, { headers:this.httpHeaders })
       .subscribe(
           res => {  console.log(res) } );
like image 109
Sudarshana Dayananda Avatar answered Nov 22 '25 14:11

Sudarshana Dayananda