如何在Ionic 3中将Base64转换为图像对象?

时间:2018-08-30 13:37:58

标签: ionic-framework ionic2 ionic3 base64 blob

我正在尝试在 Ionic 3 中上传图片,但是在Base64中获得图片,因此我想将其转换为图片文件对象。

如何转换?

这是我的组件代码

    this.camera.getPicture(options).then((imageData) => {
      let base64Image = 'data:image/jpeg;base64,' + imageData;
      this.profilePhoto['profile_photo'] = base64Image;
      let formData = new FormData();

      let blob: Blob = this.utilService.convertBase64ToImage(base64Image);
      let file = new File([blob], this.utilService.newGuid() + '.jpg', { type: 'image/jpeg' });
      let newFileObj = this.utilService.convertFileObject(file);

      formData.append('profile_photo', newFileObj);
      this.updatePhoto(formData);
    }, (err) => {
      console.log(err);
    });
  

使用此代码,我没有得到图像对象(如Web),因此如何将该base64转换为图像对象(如Web)

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的方法吗?如果您将base64正确地转换为Blob,则应该能够将blob直接放入FormData中(无需转换为File)。然后上传到您的API。

let blob: Blob = this.utilService.convertBase64ToImage(base64Image);
await this.uploadImage(blob);

uploadImage(imageBlob: Blob, fileName = "imageUpload.png") {

  let p = new Promise<void>((resolve, reject) => {

    let formData: FormData = new FormData();
    formData.append('uploadFile', imageBlob, fileName);

    let params = new HttpParams();

    this.httpClient.post('http://YOUR_API_HERE', formData,        
      {
        responseType: 'text', //Empty response is expected, no JSON
      })
      .subscribe(
        data => {
          // We don't care what we get back here...
          resolve();
        },
        error => {
          //We didn't get data back
          console.log("Error submitting image upload")
          let e = new Error("Error uploading an image");
          reject(e);
        });
  });

  return p;
}