0

I have an Spring Boot endpoint, which expects a MultipartFile, to upload a profile picture:

@RequestMapping(value="/picture", method=RequestMethod.POST)
public ResponseEntity<Void> uploadProfilePicture(@RequestParam(name="file") MultipartFile file) {
    URI uri = service.uploadProfilePicture(file);
    return ResponseEntity.created(uri).build();
}

It's working fine on Postman. Just to mention, I don't specify any Content-Type header, and I choose the file normally in the Body->form-data Postman section. Works perfectly!

But now I'm trying to request that endpoint through Ionic. First of all, I'm taking a picture using a similar code from official documentation, which stores the picture as base64:

getCameraPicture() {
  const options: CameraOptions = {
    quality: 100,
    destinationType: this.camera.DestinationType.DATA_URL,
    encodingType: this.camera.EncodingType.JPEG,
    mediaType: this.camera.MediaType.PICTURE
  }

  this.camera.getPicture(options)
    .then(imageData => {
      this.picture = 'data:image/jpeg;base64,' + imageData;
    }, 
    error => {
    });
}

The above Ionic code is working fine: the picture taken is being stored in my picture variable and I could also see it in my screen using a <img [scr]="picture"> element.

Now I want to send that picture to my endpoint, but I'm not sure how to do that. The basic idea is to call an uploadPicture method from a service:

sendPicture() {
  this.clientService.uploadPicture(this.picture)
    .subscribe(response => {
      ...
    },
    error => {
      ...
    });
}

And then implement that method in the service class:

uploadPicture(picture) {
    let formData: FormData = new FormData();
    formData.append('file', picture);
    return this.http.post(
        `${API_CONFIG.baseUrl}/clientes/picture`, 
        formData,
        { 
            observe: 'response', 
            responseType: 'text'
        }
    ); 
}

I'm not sure if it's necessary to convert that base64 picture to blob or whatever. Anyway, I'm getting a MissingServletRequestPartException from my backend: "Required request part 'file' is not present".

So how to upload a base64 image to a Spring Boot endpoint which expects a MultipartFile?

Nelio Alves
  • 1,231
  • 13
  • 34

1 Answers1

2

You need to turn your base64 data to blob then you should send it.

dataURItoBlob(dataURI) {
    var byteString = atob(dataURI.split(',')[1]);
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
    var ab = new ArrayBuffer(byteString.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    var blob = new Blob([ab], {type: mimeString});
    return blob;

  }

reference

necilAlbayrak
  • 824
  • 6
  • 9