我有一个Spring Boot端点,它希望有一个MultipartFile来上传个人资料图片:

@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();
}


在Postman上运行正常。只需提一下,我没有指定任何Content-Type标头,而是通常在Body-> form-data Postman部分中选择文件。完美的作品!

但是现在我正在尝试通过Ionic请求该端点。首先,我使用官方文档中的类似代码拍摄图片,该图片将图片存储为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 => {
    });
}


上面的Ionic代码工作正常:所拍摄的图片存储在我的picture变量中,我也可以使用<img [scr]="picture">元素在屏幕上看到它。

现在,我想将该图片发送到我的端点,但是我不确定该怎么做。基本思想是从服务中调用uploadPicture方法:

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


然后在服务类中实现该方法:

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'
        }
    );
}


我不确定是否有必要将该base64图片转换为blob或其他内容。无论如何,我从后端得到MissingServletRequestPartException:“不存在所需的请求部分'文件'”。

那么如何将base64映像上载到需要MultipartFile的Spring Boot端点呢?

最佳答案

您需要将base64数据转换为blob,然后再发送。

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

07-28 02:43
查看更多