how to upload multiple photos to the Ionic app

Asked

Viewed 433 times

-1

Good evening, I am developing an application in which will be saved some photos, I can use the camera and everything works correctly, my doubt is: How to add more than one photo ?

Follows my code:

In the camera preview:

private _getPicture(source: number, callback): void {
    if(this.platform.is('cordova')) {
      this.platform.ready().then(() =>{
        try {
          //definidno as opções e configurações da foto
          let options: CameraOptions = {
            quality: 70,
            //DATA_URL é a imagem convertida em base64, vai devolver em base64 pra gente
            destinationType: this.camera.DestinationType.DATA_URL,
            //definindo da onde vai vir, aqui se escolhe se irá vir da câmera, galeria, etc.
            sourceType: source,
            //se permite a pessoa editar a foto depois de tirar
            allowEdit: true,
            //como a imgem será salva
            encodingType: this.camera.EncodingType.JPEG,
             //escolher se a foto vai ser salva na galeria do celular
             saveToPhotoAlbum: false,
             //defenir a orientação correta
             correctOrientation: true             
          }

            this.camera.getPicture(options).then((imgData)=>{
                //ajustando a imagem, e no final ${}=> vai o que será o resultado da captura
                  let base64Image = `data:image/jpeg;base64,${imgData}`
                  callback(base64Image);
            }, err =>{
                  console.log('Problema ao capturar a foto', err)
            });
        } catch (error) {
            console.log('problema ao tirar a foto', error)
        }

      })
    }else {
      alert('Disponibilidade disponível somente no device');
    }
}

//criando método para pegar a foto da galeria
public getPictureFromGalery(callback): void{
this._getPicture(this.camera.PictureSourceType.PHOTOLIBRARY, photo =>{ 
  //pegando a foto escolhida
  callback(photo)
});
}

//criando um método para tirar a foto
public takePicture(callback): void {
this._getPicture(this.camera.PictureSourceType.CAMERA, photo =>{
  //pegando a foto tirada
  callback(photo)
});
}

On the screen ts where I choose the photo:

getPictureOptions(): void {
  //actionSheet serve para aparecer as opções, se a foto será escolhida na galeria ou tirada na hora.
  let actionSheet = this.actionSheetCtrl.create({
    title: 'Adicionar foto',
    buttons: [
      { text: 'Tirar foto', handler: () => {
        //escolhendo a opção de tirar foto no cameraprovider que foi criado, e assumindo o valor da photo para o projeto.foto
        this.cameraSrvc.takePicture(photo =>{
          this.projeto.foto = photo;
        })

      }, 
      icon: this.platform.is('ios') ? null : 'camera' },
//------------------------ Opção pegar da galeria ------------
      { text: 'Pegar galeria', handler: () =>{
        this.cameraSrvc.getPictureFromGalery(photo =>{
          this.projeto.foto = photo;
        })

      }, icon: this.platform.is('ios') ? null : 'images'},
      //o role 'destructive' deixa o botao vermelho
      {text: 'Cancelar', role: 'destructive', 
      icon: this.platform.is('ios') ? null : 'close'
    ,handler: () => {
        //cancela a ação
      }, }
    ]
  });
  actionSheet.present();

}

Where the photo will be displayed:

 <ion-row>
                        <ion-item text-center>
                            <button ion-button clear (click)="getPictureOptions()"><ion-icon name="camera" item-left></ion-icon> Selecionar Foto</button>
                          </ion-item>
                    </ion-row>
                    </ion-col>
                    </ion-row>

                    <ion-item *ngIf="projeto.foto">
                        <img [src]="projeto.foto">
                      </ion-item>

1 answer

0


  • Gesiel my question is how to add one by one even, you know ? i created 2 photo fields, but when I take a photo the same is added in both fields

  • It is that you are always putting the photos in the same variable "this.projecto.foto = photo;". If you want multiple photos, you have to have an array of photos. Then "this.projecto.foto" has to be an array, not a string. When you receive the new photo, you make a "this.projecto.foto.push(photo)". And in HTML you will have to do a FOR to display all the images in the array. If you want an example, you have this: https://www.9lessons.info/2017/04/ionic2-angular2-camera-native-multiple.html

  • this.projecto.foto comes from the bank, where photo is a capo from there, how do I turn this field into an array ?

  • Guy even consgui, but gave a very big payload error 'Payload Too Large'

  • Problem solved, thanks Gesiel!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.