【问题标题】:How to convert Base64 to Image Object in Ionic 3?如何在 Ionic 3 中将 Base64 转换为图像对象?
【发布时间】:2019-02-05 11:37:05
【问题描述】:

我正在尝试在 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 的图像对象

【问题讨论】:

    标签: ionic-framework ionic2 ionic3 base64 blob


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-08-31
      • 1970-01-01
      • 2017-06-29
      • 2017-09-24
      • 1970-01-01
      • 2019-12-08
      • 1970-01-01
      • 1970-01-01
      • 2014-11-03
      相关资源
      最近更新 更多