首页 文章

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

提问于
浏览
3

我正在尝试上传 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

    你能尝试这样的东西吗?如果您正确地将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;
    }
    

相关问题