Не удается преобразовать base64 в путь к изображению в Ionic 4

#ionic-framework #ionic4

#ionic-framework #ionic4

Вопрос:

Я работаю над своим приложением Ionic 4, и я использовал плагин camera для загрузки изображений, и я преобразовал изображение в base64 для показа изображения, но проблема в том, что я не могу преобразовать base64 в правильный путь к изображению для отправки его в API.

Это мой editimage.page.html:

 <ion-item class="newitem2">
    <ion-avatar class="image-center">
        <img name="profile_pic" [src]="this.userdetailsedit.value.profile_pic"/>
        <ion-icon (click)="presentActionSheet()" class="myicon11" name="create"></ion-icon>
    </ion-avatar> 
</ion-item>
  

Это мой editprofile.page.ts:

   async UpdateUserDetails(){
    this.storage.get('USER').then(userde => {
      if (userde) {
        this.userdetails = userde;
        const userdetailseditss = {
          first_name: this.userdetailsedit.value.first_name,
          last_name: this.userdetailsedit.value.last_name,
          mobile: this.userdetailsedit.value.mobile,
          profile_pic: this.userdetailsedit.value.profile_pic,
        };
        this.chakapi.UserProfileUpdate(userdetailseditss, 'userUpdateProfile/'   this.userdetails.id).subscribe((data) => {
          console.log(data);
        }, error => { 
          console.log(error); });
      }
    });
  }

  async imageuserchoose(sourceType){
    const options: CameraOptions = {
      quality: 76,
      sourceType: sourceType,
      destinationType: this.camera.DestinationType.FILE_URI,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      saveToPhotoAlbum: true,
      correctOrientation: true,
    }

    this.camera.getPicture(options).then((imageData) => {
    if (sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {
      let path = imageData.substring(0, imageData.lastIndexOf('/')   1);
      let filename = imageData.substring(imageData.lastIndexOf('/')   1);
      let index = filename.indexOf('?');
      if (index > -1) {
        filename = filename.substring(0,index);
      }
      this.file.readAsDataURL(path, filename).then(data => {
          this.imagepic = data;
          this.userdetailsedit.patchValue({
            profile_pic: data,
          });
      });
  }
  if (sourceType === this.camera.PictureSourceType.CAMERA) {

      let filename = imageData.substring(imageData.lastIndexOf('/')   1);
      let path = imageData.substring(0, imageData.lastIndexOf('/')   1);
      this.file.readAsDataURL(path, filename).then(data => {
          this.imagepic = data;
          this.userdetailsedit.patchValue({
            profile_pic: data,
          }); 
      });
  }
    }, (err) => {
    });
  }

  async presentActionSheet() {
    const actionSheet = await this.actionSheetController.create({
      header: 'Select Image Source',
      backdropDismiss:true,
      buttons: [{
        text: 'Choose From Gallery',
        icon: 'images',
        cssClass: 'myActionSheetBtnStyle',
        handler: () => {
          this.imageuserchoose(this.camera.PictureSourceType.PHOTOLIBRARY);
        }
      },
      {
        text: 'Use Camera',
        icon: 'camera',
        cssClass: 'myActionSheetBtnStyle',
        handler: () => {
          this.imageuserchoose(this.camera.PictureSourceType.CAMERA);
        }
      }]
    });
    await actionSheet.present();
  }
}
  

Проблема в том, что когда я отправляю изображение в API, это base64, и я не могу преобразовать его перед отправкой.

Любая помощь приветствуется.

Ответ №1:

Пожалуйста, попробуйте это. Для этого вы можете использовать встроенный плагин file transfer. Это решит вашу проблему.

В ts файле:

 async UpdateUserDetails(){ 
   if(this.imagepic amp;amp; this.fileUploadName) {
    let  fileTransfer = this.transfer.create();
    let options: FileUploadOptions = {
      fileKey: 'profile_pic',
      fileName: this.fileUploadName,
      headers: {}     
  }  
  options.params = {
    first_name: this.userdetailsedit.value.first_name,
    last_name: this.userdetailsedit.value.last_name,
    mobile: this.userdetailsedit.value.mobile,
    old_password:  this.userdetailsedit.value.old_password,
    password: this.userdetailsedit.value.password,    
  };
  this.storage.get('USER').then(userde => {
    if (userde) {
    this.userdetails = userde;
   fileTransfer.upload(this.imagepic, this.apiUrl 'userUpdateProfile/' this.userdetails.id, options)
   .then((data) => {
     if(data amp;amp; data.responseCode==200){
      let response=JSON.parse(data.response);
      if(response.status === "success"){
      this.storage.set('ID', response.data.id);
      this.storage.set('USER', response.data);
      this.modalController.dismiss();
      } else{
        loading2.dismiss();
      }
     }else{
       //show error msg  
     }
   }, (err) => {     
    console.log('upload err ::',err);
   });
  }
 });
}
}
async imageuserchoose(sourceType){
    const options: CameraOptions = {
      quality: 76,
      sourceType: sourceType,
      destinationType: this.camera.DestinationType.FILE_URI,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      saveToPhotoAlbum: true,
      correctOrientation: true,
      // allowEdit: true,
    }

    this.camera.getPicture(options).then((imageData) => {    
      let filename,path;
      this.imagepic = imageData;
        if (sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {
             path = imageData.substring(0, imageData.lastIndexOf('/')   1);
             filename = imageData.substring(imageData.lastIndexOf('/')   1);
            let index = filename.indexOf('?');     
            if (index > -1) {
              filename = filename.substring(0,index);
            }      
        }
        if (sourceType === this.camera.PictureSourceType.CAMERA) {
             filename = imageData.substring(imageData.lastIndexOf('/')   1);
             path = imageData.substring(0, imageData.lastIndexOf('/')   1);
            console.log(path,'FileName::', filename);            
        }
        this.fileUploadName=filename;
        this.file.readAsDataURL(path, filename).then(data => {          
          this.userdetailsedit.patchValue({
            profile_pic: data,
          }); 
      });
    }, (err) => {
     // Handle error
    });
  }
  

Это решит вашу проблему.

Комментарии:

1. У меня есть сомнения в этом. У меня есть сценарий для захвата изображения и назначения его вкладке Img. Для этого также нужно использовать «file»?

2. Для чего нужны «имя файла» и «путь»? это только для целей API?

3. @AnandRaj. Это только для целей API для передачи файла.

4. @AnandRaj.Используя это: передача файлов.загрузка (this.imagepic, this.apiUrl). Изображение будет загружено, и вы также можете отправить параметры вместе с ним, если у вас есть форма.

5. @filol. проблема в URI. Проверьте это: github.com/sitewaerts/cordova-plugin-document-viewer/issues/83